sql 左连接,右连接,等值连接,case-when

来源:互联网 发布:大数据时代财务转型 编辑:程序博客网 时间:2024/05/18 01:07

1.内容

left join(左联接) 返回包括左表中的所有记录和右表中联结字段相等的记录
right join(右联接) 返回包括右表中的所有记录和左表中联结字段相等的记录
inner join(等值连接) 只返回两个表中联结字段相等的行
现以下两张t_a,t_b表
这里写图片描述
这里写图片描述

2.左链接

select * from t_a a left join t_b  b on a.aid = b.bid

这里写图片描述
左连接会以左表为基础表返回全部数据,而右表只会返回全符合条件的数据

3.右连接

select * from t_a a right join t_b  b on a.aid = b.bid

这里写图片描述
右连接会以右表为基础表返回全部数据,而左表只会返回全符合条件的数据

4.等值连接

select * from t_a a inner join t_b  b on a.aid = b.bid

这里写图片描述
等值连接会返回条件相等的数据

5.case-when

现有下表t_city
这里写图片描述
现将id=1 替换为北京,2=上海,3=广州,4=深圳 ,否则为其他

select  case a.idwhen 1 then '北京' when 2 then '上海'when 3 then '广州'when 4 then '深圳'else  '其他' end city_name,a.numberfrom t_city a

或者

select  case when a.id=1 then '北京' when a.id=2 then '上海'when a.id=3 then '广州'when a.id=4 then '深圳'else  '其他' end city_name,a.numberfrom t_city a

这里写图片描述
前一个为简单Case函数 ,后一个为Case搜索函数 ,第二个更为灵活

原创粉丝点击