使用背景:学生表(student)、课程表(course)、考试表exam
SQL内连接(inner join)
select a.uid,a.name,a.age,a.sex,b.cid,b.cname,b.credit,c.score
from exam c
inner join student a on c.uid=a.uid
inner join course b on c.cid=b.cid
where c.uid=1 and c.cid=2;
<1>区分大表和小表,按照数据量来区分,小表永远是整表扫描,然后去大表搜索,一般在大表中创建索引。例:从exam大表中取出所有的c.uid和c.cid,然后拿着这些uid和cid去student和course小表中搜索
<2>可结合分组、排序操作,进行更精确的搜索
<3>先执行on连接产生临时表,再执行where在临时表中筛选符合条件的数据
结合limit分页优化SQL语句
select a.id,a.email,a.passward from t_user a inner join(select id from t_user limit 150000,10) b on a.id=b.id;
在()中创建一个临时表作为小表,提升SQL效率
SQL外连接(outer join)
SQL左连接查询(left join)
SELECT a.属性名列表,b.属性名列表 FROM table_name1 a LEFT JOIN table_name2 b on a.id=b.id;
//把left这边的表所有数据显示出来,在右表中不存在相应数据,则显示NULL
select a.*,b.* from student a left outer join exam b on a.uid=b.uid;
SQL右连接查询(right join)
//把right这边的表所有数据显示出来,在左表中不存在相应数据,则显示NULL
select a.*,b.* from student a right outer join exam b on a.uid=b.uid;
实际应用场景:查询在当前连接中为空的属性
select a.* from student a left join exam b on a.uid=b.uid where b.cid is null;
//not in 对于索引的命中并不高,推荐使用外连接
select * from student where uid not in (select distinct uid from exam);
内连接和外连接的区别:
<1>对于inner join内连接,过滤条件写在where的后面和on连接条件里面,效果是一样的。
对于outer join外连接,在判断null和限制条件的情况下,限制条件写在on里面,where条件过滤只判断null的情况
select a.* from student a left join exam b on a.uid=b.uid and b.cid=3 where b.cid is null;