繁体   English   中英

MySQL 查询仅获取一条记录:end_date 为 null 或 max(end_date)

[英]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 = 77organization_id = 16end_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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM