gpt4 book ai didi

mysql - 从左表中检索所有记录并从右表中检索匹配记录

转载 作者:行者123 更新时间:2023-11-29 03:48:04 24 4
gpt4 key购买 nike

我正在尝试四个查询来检索 Table1 中的所有记录和 Table2 中的匹配记录,但我的查询只返回两个记录而不是三个。

Table1:

EmpId name
1 xyz1
2 xyz2
3 xyz3

Table2:
EmpId dateIn
1 2015-05-05
2 2015-05-05

Required result:

EmpId name DateIn
1 xyz1 2015-05-05
2 xyz2 2015-05-05
3 xyz3 NULL

select Table1.EmpId, Table1.name, Table2.dateIn from Table1 left join Table2 on Table1.empid=Table2.empid where date_format(Datein, '%Y-%m-%d')='2015-05-05'

select Table1.EmpId, Table1.name, Table2.dateIn from Table1 left join Table2 on Table1.empid=Table2.empid where date_format(Datein, '%Y-%m-%d')='2015-05-05' group by Table1.EmpId, Table1.name, Table2.dateIn

select Table1.EmpId, Table1.name, Table2.dateIn from Table1,Table2 where Table1.empid=Table2.empid and date_format(Datein, '%Y-%m-%d')='2015-05-05' group by Table1.EmpId, Table1.name, Table2.dateIn

select Table1.EmpId, Table1.name, Table2.dateIn from Table1,Table2 where Table1.empid=Table2.empid and date_format(Datein, '%Y-%m-%d')='2015-05-05'

请帮忙。

最佳答案

你想要一个左连接。

select t1.*, t2.datein
from table1 t1
left join table2 t2
on t1.empid = t2.empid

在您的查询中,您在 where 子句中引用 datein 的方式将自动消除 datein 为空的任何行,破坏了 left join 的外部性。

如果你想过滤日期,但对于不匹配的那些返回null,你必须将它移动到on子句,像这样:

select t1.*, t2.datein
from table1 t1
left join table2 t2
on t1.empid = t2.empid and date(t2.datein) = '2015-05-05'

或者,如果您想将它放在 where 子句中,出于语义原因,您还需要检查 is null,如下所示:

select t1.*, t2.datein
from table1 t1
left join table2 t2
on t1.empid = t2.empid
where date(t2.datein) = '2015-05-05' or t2.datein is null

此方法需要注意的是,如果 datein 在第二个表中可以有空值,则它可以为每个 empid 返回多行。

我个人的偏好是将日期过滤器作为连接谓词的一部分,而不是 where

关于mysql - 从左表中检索所有记录并从右表中检索匹配记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30211542/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com