MySQL命令大全——连接查询
有如下两张表student表和course表
其中cou_id是右边表的外键
一、左连接
查询过程中,以左边的表为准,去右表中寻找数据,如果没有就用NULL补齐
语法:
select s.s_id, s_name, c_name from student as s left join course as c on s.cou_id = c.c_id;
select s.s_id, s_name, c_name from course as c left join student as s on s.cou_id = c.c_id;
二、右连接
查询过程中,以右边的表为准,去左表中寻找数据,如果没有就用NULL补齐
语法:
select s.s_id, s_name, c_name from student as s right join course as c on s.cou_id = c.c_id;
select s.s_id, s_name, c_name from course as c right join student as s on s.cou_id = c.c_id;
由上面可以看出,左右连接只是所选的主表不同而改变查询结果,所以,有时候左右表是可以互相转换的;
三、内连接
查询左右表都有的数据
语法:
select s.s_id, s_name, c_name from course as c inner join student as s on s.cou_id = c.c_id;
四、mySQL中暂不支持外连接
注:在连接查询中,where,having等关键字同样可以使用