sql语句

作者: 浮生_1918 | 来源:发表于2019-06-25 16:10 被阅读0次

sql中in和exist的区别:

1、in先子查询,后主查询

2、exist先主查询,后子查询。子查询中,如果结果为TRUE保留,否则删除。

应用场景:in适合子查询结果少的,exist适合主查询结果较少的。

具体请参考:https://www.cnblogs.com/liyasong/p/sql_in_exists.html

select * from user where user_id in (select * from user where age = 18);

select * from user where user_id exists (select * from user where age = 18)

sql中left join和right join以及inner join

1、left join 以左表为主,right join以右表为主。

2、inner join以左表和右表连接满足条件的为主,取交集。

具体请参考:https://www.cnblogs.com/hongten/p/hongten_sql_join.html

select * from student a left join score b on a.id=b.id

select * from student  a right join score b on a.id=b.id

sql中group by的使用:

1、select中的列名(必须在group中)和列函数。

但是当有了join的时候就不必遵循此规则,例如:SELECT a.sid,a.sname from s a join sc b on a.SID=b.SID GROUP BY b.SID having COUNT(*)=2

sql中case when的用法:

1、与GROUP BY 结合,自定义列联表统计

select  country,sum(case when sex='1' then population else 0 end),sum(case when sex='2' then population else 0 end) from T GROUP BY country;

2、与Group by结合,自定义分组统计

3、与distinct结合,去重分组统计

4、根据条件有选择的UPDATE

5.两个表数据是否一致的检查

---in---

select keyCol,CASE WHEN keycol IN (select keyCol from tbl_b) THEN 'matched' ELSE 'unmatched' END label from tbl_a;

---exist---

select keyCol,CASE WHEN keycol EXIST (select keyCol from tbl_b) THEN 'matched' ELSE 'unmatched' END label from tbl_a;

具体请参考:https://www.jianshu.com/p/f098606391ea

sql中模糊查询like:

可以%a,%a%,a%,%a%f

你能想到的,都可以试一下*_*

sql中的union和union all:

union:取并集,且去掉重复行,并按照一定规则排序。

union all:取并集,包括重复行,不排序。

使用union或者union all的时候要注意,两个sql的字段以及字段类型要一致。

Oracle的语法和Mysql是不一样的,这个要注意:比如Mysql没有rownum函数,你可以用:SELECT @rownum:=@rownum+1 AS rownum,sc.* FROM (SELECT @rownum:=0) r, sc 或者其他方法来实现。

相关文章

网友评论

      本文标题:sql语句

      本文链接:https://www.haomeiwen.com/subject/bscxcctx.html