MySQL 连接查询 (俗称连表查询) 分为内连接, 外连接, 自然连接
测试数据如下:
- create table student(id int primary key auto_increment,name varchar(10));
- insert into student values(null,'xiaohong'),(null,'xiaoming'),(null,'xiaoliang');
- create table score(id int primary key auto_increment,stu_id int not null, score decimal(5,2));
- insert into score values(null,1,200.35),(null,2,300.45),(null,3,400.56);
补充:
decimal(10,2) 中的 "2" 表示小数部分的位数, 如果插入的值未指定小数部分或者小数部分不足两位则会自动补到 2 位小数,
若插入的值小数部分超过了 2 为则会发生截断, 截取前 2 位小数.
"10" 指的是整数部分加小数部分的总长度, 也即插入的数字整数部分不能超过 "10-2" 位, 否则不能成功插入, 会报超出范围的错误.
内连接
inner join/join
由于 MySQL 默认是内连接, 所以 join 等同于 inner join
内连接返回的是符合连接条件并且两个表中都有对应数据存在的记录.
如果符合条件 但是某一字段值为 null, 查出来的是 null
举例:
SELECT stu.id,stu.name,s.score from student as stu join score as s on stu.id=s.stu_id;
连接条件分析:
连接条件可以使用 on using where
区别: on 是在连表查询中, 任何情况下都可以使用 on, 而且建议使用 on.
on 实在连表的过程中, 根据 on 条件判断是否保留连表的结果.
using 是在连表查询的字段名一致时, 可以使用. 如 using(id).using 条件中
使用的字段, 返回结果中只有一遍.
where 是在连表操作完成后, 再根据 where 条件进行数据过滤. 效率低不建议这样.
外连接
外连接查询时, 允许另一方存在与之不匹配的数据. 外连接的连接条件不可使用 where,
必须使用 using 和 on 的一种, 其他都与内连接一致.
左外连接 (left outer join/ left join )
左表为主表, 即使右表没有与左表匹配的记录, 也返回左表的记录. 而右表与左表不匹配的记录将会被忽略.
举例:
select score.score,student.name from score left join student on score.stu_id=student.id;
右外连接 (right outer join / right join)
右表为主表, 即使左表没有与之匹配的记录, 也返回右表的记录.
举例:
select score.score ,student.name from score right join student on score.stu_id=student.id;
全外连接 (full join):MySQL 暂不支持, 可以用 union 模拟实现.
自然连接
- natural join (同 join)
- natural left join (同 left join)
- natural right join (同 right join)
自然连接会自动判断, 以两个表中相同的字段为连接条件, 返回查询结果.
注意: 内连接不写连接条件会出现笛卡尔积的结果, 应该避免这种情况, 而外连接不写连接条件会报错
来源: http://www.bubuko.com/infodetail-3298827.html