[英]MySQL query to get only one record: either when end_date is null or max(end_date)
我有下表( employee_organization
):
ID | 員工ID | 組織編號 | 開始日期 | 結束日期 |
---|---|---|---|---|
1個 | 77 | 16 | 2021-01-01 | 2021-06-30 |
2個 | 11 | 23 | 2020-01-01 | 2021-05-27 |
3個 | 77 | 16 | 2021-08-01 | 2021-08-31 |
4個 | 77 | 16 | 2021-09-01 | NULL |
我需要一個查詢來過濾掉employee_id = 77
、 organization_id = 16
和end_date is null
。 如果沒有找到匹配的行,則返回帶有max(end_date)
的行。 因此,在上面的示例表中,只應返回id=4
的行。
SELECT *
FROM table
WHERE {needed conditions}
ORDER BY end_date IS NULL DESC, end_date DESC LIMIT 1
一個通用的解決方案是使用相關子查詢來查找每個員工的最大日期(首先是空值):
select *
from t
where end_date <=> (
select end_date
from t as x
where x.employee_id = t.employee_id
order by end_date IS NOT NULL, end_date desc
limit 1
)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.