本篇为自用备忘技巧。主要是做sql练习题(学生,课程、老师表混合练习)后所掌握的小技巧。练习题网址:https://blog.csdn.net/fashion2014/article/details/78826299
1.用到自连接的情况:
找出字段值同时满足n个条件的记录;
用法:先子查询再inner join 或者 先全表inner join 再筛选,暂时不太清楚这两种做法对效率的影响
2.using 关键字
用于需要关联表的场景。
等效的关键字有on、where。
对比起on和where关键字做到的表关联效果,
using可以自动省略两关联表中的关联列, 如下面的sql,运行后t1表和t2表的关联列sid只会出现一次
-- using写法
select * from
(select sid,score as score1 from grade where cid = '01') as t1
inner join
(select sid,score as score2 from grade where cid = '02') as t2
using(sid) ;
-- 等价写法:on 和 where关键字
select * from
(select sid,score as score1 from grade where cid = '01') as t1
inner join
(select sid,score as score2 from grade where cid = '02') as t2
where t1.sid = t2.sid ;
select * from
(select sid,score as score1 from grade where cid = '01') as t1
inner join
(select sid,score as score2 from grade where cid = '02') as t2
on t1.sid = t2.sid ;
using、where、on关键字用来关联表的效果对比:
3.做联表操作时,要考虑可能会出现null的情况,并做处理。
联表是以其他表记录去匹配主表记录,如果匹配补上,则空缺的部分会补null
如果此处需要处理空值null,可以用以下函数处理:
if(和该字段相关的表达式,值A, 值B)
case when
4.关于找出某集合元素一致的集合,有个骚操作是group_concat把所有的元素都拼接成字符串,再对比。