2016-08-31 68 views
0

我有兩個表:Mysql的選擇 - 全部由左,只有匹配的右表

  1. employees

    [ID,名字,姓氏,狀態]

  2. absence

    [id,employee_id,reason_type,date_from,date_to

我可以這樣做:

SELECT e.first_name, e.last_name, e.status, a.reason_type FROM employees e JOIN absence a ON e.id=a.employee_id 
WHERE curdate() between date_from and date_to 

,但它會給我只在absence表中找到這些員工。

有沒有辦法讓所有員工的名單和他們的狀態(對於那些在absence表匹配條件currdate() between date_from and date_to回「是」和reason_type找到)和其他人說沒有和空值reason_type

感謝。

+1

做一個'LEFT JOIN'。 – jarlh

回答

2

你正在尋找一個left join,但你必須要小心的where條款:

SELECT e.first_name, e.last_name, e.status, a.reason_type 
FROM employees e LEFT JOIN 
    absence a 
    ON e.id = a.employee_id AND 
     curdate() between a.date_from and a.date_to ; 
0

你想要一個LEFT JOIN。這正是你想要的:連接左側的所有值,如果沒有匹配,則右側爲null

還有(不出意料)一個RIGHT JOIN,這反過來。

enter image description here

0

您可以使用下面的查詢..

SELECT e.first_name, e.last_name, e.status, a.reason_type 
FROM employees e 
LEFT JOIN absence a ON e.id=a.employee_id 
WHERE curdate() between date_from and date_to 
相關問題