MySQL 查询仅获取一条记录:当 end_date 为 null 或 max(end_date)
MySQL query to get only one record: either when end_date is null or max(end_date)
我有以下 table (employee_organization
):
ID
employee_id
organization_id
start_date
end_date
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
的记录。如果没有找到匹配的行,那么 return 与 max(end_date)
的行。因此,在上面的示例 table 中,只有带有 id=4
的行应该被 returned.
SELECT *
FROM table
WHERE {needed conditions}
ORDER BY end_date IS NULL DESC, end_date DESC LIMIT 1
我有以下 table (employee_organization
):
ID | employee_id | organization_id | start_date | end_date |
---|---|---|---|---|
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
的记录。如果没有找到匹配的行,那么 return 与 max(end_date)
的行。因此,在上面的示例 table 中,只有带有 id=4
的行应该被 returned.
SELECT *
FROM table
WHERE {needed conditions}
ORDER BY end_date IS NULL DESC, end_date DESC LIMIT 1