合并MySQL SELECT语句

问题描述 投票:-3回答:1

我有下表tbl_crps,请注意,列[[crp多次出现,但是idstarts_on在具有相同 crp

id | crp | starts_on | ------------------ 1 | 20 | 2020-02-09 | 2 | 31 | 2019-06-05 | 3 | 20 | 2018-01-10 | 4 | 31 | 2021-07-03 | 5 | 58 | 2022-01-01 | 6 | 58 | 2025-02-02 |
我需要在以下情况下提取记录:

  1. 如果是

    crp

,则存在一个或多个具有过去starts_on的记录,那么在那些具有crp的记录(具有过去日期的记录)中,具有最大id的记录必须是返回
  • 如果用于

    crp

  • ,则没有过去日期的记录,则在所有具有该[[crp]的记录中,具有最大ID的记录我可以成功选择符合以下条件的第一个条件的记录。SELECT * FROM tbl_crps AND id IN (SELECT MAX(b.id) FROM tbl_crps b WHERE b.starts_on <= "2020-10-02")

    将返回ID为3和2的记录。

    我需要实现的是将结果[不在过去,而

    crp

    不在第一个结果集中的那些记录添加到结果中。

    有可能吗?也许是这样吗?

    SELECT * FROM tbl_crps a WHERE id IN ( SELECT MAX(a.id) FROM tbl_crps a WHERE a.starts_on <= "2020-10-02" ) UNION ( SELECT * FROM tbl_crps b WHERE id IN ( SELECT MAX(c.id) FROM tbl_crps c WHERE c.starts_on > "2020-10-02" AND c.crp NOT IN ( SELECT d.crp FROM tbl_crps d WHERE id IN ( SELECT MAX(e.id) FROM tbl_crps e WHERE e.starts_on <= "2020-10-02") ) ) ) 我有下表tbl_crps,请注意,列crp出现了不止一次,但id和starts_on在具有相同crp的记录中将始终不同。 id | crp | starts_on | ----------------...
    mysql
    1个回答
    0
    投票
    此返回

    id crp starts_on 2 31 2019-06-05 3 20 2018-01-10 5 58 2022-01-01 6 58 2025-02-02

    根据我对要求的理解,这似乎是正确的。简而言之

    1 - NOT included because its date is in the past ('current' date = 2020-10-02) and its ID is NOT the greatest among records in the past with that CRP. 2 - included because its date is in the past and its ID is the greatest among records with that CRP which have dates in the past. 3 - date is in the past, ID is greatest for that CRP with date in the past 4 - NOT included because date is in the future, but CRP is included in recs from first subquery. 5 - date is in the future, and CRP does not occur in first subquery 6 - date is in the future, and CRP does not occur in first subquery

    db<>fiddle here
    最新问题
    © www.soinside.com 2019 - 2024. All rights reserved.