如何通过比较 MySQL Workbench 中的日期进行过滤

How to filter by comparing the dates in MySQL Workbench

我有一个 table 看起来像这样的:

ID   B     C      date01        date02       date03
11  xxx   xxxx   2020-05-01    2020-05-02   2020-06-02
11  xxx   xxxx   2020-06-01    2020-06-03   2020-05-02
11  xxx   xxxx   2020-07-01    2020-07-03   2020-06-30
11  xxx   xxxx   2020-07-01    2020-06-03   2020-06-30
11  xxx   xxxx   2020-01-01    2020-01-08   2020-05-02
11  xxx   xxxx   2020-02-01    2020-01-31   2020-05-02
22  xxx   xxxx   2020-05-01    2020-05-02   2020-06-02
22  xxx   xxxx   2020-06-01    2020-06-03   2020-05-02
22  xxx   xxxx   2020-07-01    2020-07-03   2020-06-30
22  xxx   xxxx   2020-07-01    2020-06-03   2020-06-30
22  xxx   xxxx   2020-01-01    2020-01-08   2020-05-02
22  xxx   xxxx   2020-02-01    2020-01-31   2020-05-02

我想要 return 除了每个 ID 的这三个日期的最新日期之外的所有内容,并且 date02 不能晚于 date03,我当前的输出将给我这个 where date02 > date03:

11  xxx   xxxx   2020-07-01    2020-07-03   2020-06-30

预期输出:

11  xxx   xxxx   2020-07-01    2020-06-03   2020-06-30
22  xxx   xxxx   2020-07-01    2020-06-03   2020-06-30

我试过这个:

SELECT 
    id,
    B,
    C,
    max(date01),
    max(date02), 
    max(date03),  
FROM 
    table
WHERE
    'date02' < 'date03'
GROUP BY id

我添加了 WHERE 'date02' < 'date03' 但是为什么输出仍然有 date02>date03 的记录??我是 SQL 的新手,请帮忙...

您可以使用相关子查询和元组相等性来做到这一点:

select t.*
from mytable t
where (t.date01, t.date02, t.date03) = (
    select t1.date01, t1.date02, t1.date03 
    from mytable t1 
    where t1.id = t.id
    order by t1.date01 desc, t1.date02 desc, t1.date03 desc
    limit 1
)

为了提高此查询的性能,您可以在 (id, date01, date02, date03).

上创建复合索引

也可以用row_number(),如果你是运行 MySQL 8.0:

select *
from (
    select 
        t.*, 
        row_number() over(partition by id order by date01 desc, date02 desc, date03 desc) rn
    from mytable t
) t
where rn = 1

Demo on DB Fiddle:

ID | B   | C    | date01     | date02     | date03    
-: | :-- | :--- | :--------- | :--------- | :---------
11 | xxx | xxxx | 2020-07-01 | 2020-07-03 | 2020-06-30
22 | xxx | xxxx | 2020-07-01 | 2020-07-03 | 2020-06-30