簡體   English   中英

從左表中檢索所有記錄,並從右表中檢索匹配的記錄

[英]Retriving all records from left table and matching records from right

我正在嘗試四個查詢,以從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為null的任何行, 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

這樣就可以了。
SQL查詢

declare @Table1 as table( empid tinyint, name varchar(10))
insert into @table1 values (1,'xyz1')
insert into @table1 values (2,'xyz2')
insert into @table1 values (3,'xyz3')

declare @Table2 as table (Empid tinyint, datein date)
insert into @Table2 values(1,'2015-05-05')
insert into @Table2 values(2,'2015-05-05')


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

結果

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM