SQL左链接问题

猴子我是唐僧啊 2020-05-23 09:35:17
各位大佬,碰到一个SQL语句不会写,哪位大佬可以教一下?
具体的需求为:不论我后面写的where语句有没有找到数据,表1中的数据行全部都需要找出来,表2根表1不匹配的就NULL

表1:
id name depart att
1 张三 IT 1
2 李四 IT 2
3 王五 IT 1
4 钱六 IT 1
5 王八 IT 3


表2:
ID dept att moth
1 IT 1 2020-05
2 IT 2 2020-05

select * from 表1 left join 表2 on 表1.att= 表2.att where moth='2020-05'
语句查询得到的结果如下 :
**************************
1 张三 IT 1 1 IT 1 2020-05
2 李四 IT 2 2 IT 2 2020-05
3 王五 IT 1 1 IT 1 2020-05
4 钱六 IT 1 1 IT 1 2020-05

如果我想要的结果是如下这样:

1 张三 IT 1 1 IT 1 2020-05
2 李四 IT 2 2 IT 2 2020-05
3 王五 IT 1 1 IT 1 2020-05
4 钱六 IT 1 1 IT 1 2020-05
5 王八 IT 3 null null null null

这个语句我需要怎么写?
...全文
80 1 打赏 收藏 转发到动态 举报
写回复
用AI写文章
1 条回复
切换为时间正序
请发表友善的回复…
发表回复
Yole 2020-05-23
  • 打赏
  • 举报
回复



create table #表1
(id int,   name char(10) , depart char(10) ,  att int

)

insert into  #表1
select 1 ,     '张三',      'IT',           1 union all
select 2 ,     '李四' ,     'IT',           2 union all
select 3 ,     '王五' ,     'IT',           1 union all
select 4 ,     '钱六' ,    'IT',           1 union all
select 5 ,     '王八' ,    'IT',           3


create table #表2
(id int,   dept char(10) , att int ,moth char(10) ,

)  

insert into   #表2
select 1 ,        'IT',        1   ,     '2020-05' union all
select 2 ,        'IT',         2   ,     '2020-05'


select * from #表1  left join #表2 on #表1.att=  #表2.att  and  #表2.moth='2020-05'

/*
id          name       depart     att         id          dept       att         moth
----------- ---------- ---------- ----------- ----------- ---------- ----------- ----------
1           张三         IT         1           1           IT         1           2020-05   
2           李四         IT         2           2           IT         2           2020-05   
3           王五         IT         1           1           IT         1           2020-05   
4           钱六         IT         1           1           IT         1           2020-05   
5           王八         IT         3           NULL        NULL       NULL        NULL

(5 行受影响)


*/

34,576

社区成员

发帖
与我相关
我的任务
社区描述
MS-SQL Server相关内容讨论专区
社区管理员
  • 基础类社区
  • 二月十六
  • 卖水果的net
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧