MYSQL 的表联结


                                                                 a表
id name
1  张三
2  李四
3  王五
                                                                b表
id age parent_id
1 23 1
2 34 2
3 34 z
注:a的id和b的parent_id关联。
(1)内部联结

select a.*,b.* from a inner join b on a.id = b.parent_id;

结果:

1   张三 1 23 1
2   李四 2 34 2

(2)左外连接(左表的所有元素都有)

select a.*,b.* from a left join b on a.id=b.id;

结果:

1  张三 1 23 1
2   李四 2 34 2
3   王五 null null null
(3)右外连接(右表的所有元素都有)

select a.*,b.* from a right join b on a.id = b.parent_id;

结果:

1  张三 1 23 1
2   李四 2 34 2
null   null 3 34 4
(4)完全连接(返回左表和右表中所有行,若某行在另外一个表中无匹配,则另一表中的相应行为null)

select a.*,b.* from a full join b on a.id=b.parent_id;(此种方式mysql不支持)

可以用这种方式实现:select a.*,b.* from a left join b on a.id=b.id union select a.*,b.* from a right join b on a.id = b.parent_id;

结果:

1  张三 1 23 1
2  李四 2 34 2
3  王五 null null null
null  null 3 34 4

(5)等值连接(结果和内部联结一样)

select a.*,b.* from a,b where a.id = b.parent_id;

结果:

1   张三 1 23 1
2   李四 2 34 2

(6)联结多个表(独立的,与上面没有关系)

select a.*,b.*,c.* from a,b,c where a.id=b.id and c.id=a.id and order_num=20005;



猜你喜欢

转载自blog.csdn.net/g1607058603/article/details/80691082