簡體   English   中英

MySQL選擇-全部從左開始,僅匹配右表

[英]Mysql select - all from left and only matching right table

我有兩個表:

  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

謝謝。

您正在尋找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 ;

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

(不出所料)還有RIGHT JOIN ,它的作用恰恰相反。

在此處輸入圖片說明

您可以使用以下查詢。

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

暫無
暫無

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

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