0

我想返回 5 月(2019 年 5 月)公开的所有行,所以如果在 5 月底之前的任何时候将一行变成草稿(而不是返回公开),我不想要它。例如:

id | post_id | status | date
-------------------------
 1 | 1       | draft  | 2019-03-25
 2 | 1       | public | 2019-04-02
 3 | 1       | draft  | 2019-05-25
 4 | 2       | draft  | 2019-03-10
 5 | 2       | public | 2019-04-01
 6 | 2       | draft  | 2019-06-01

上面的预期结果将返回post_id 2,因为它在 5 月底之前的最后一次状态更改是 to public

post_id 15 月底之前又被放回草稿,所以不会被收录。

我不确定如何使用正确的连接或子查询来尽可能高效地执行此操作。

4

2 回答 2

1

您似乎想要截至 2019-05-31 的状态。相关子查询似乎是最简单的解决方案:

select t.*
from t
where t.date = (select max(t2.date)
                from t t2
                where t2.post_id = t.post_id and
                      t2.date <= '2019-05-31'
               );

要获取公开的,只需添加一个WHERE条件:

select t.*
from t
where t.date = (select max(t2.date)
                from t t2
                where t2.post_id = t.post_id and
                      t2.date <= '2019-05-31'
               ) and
      t.status = 'public';

出于性能考虑,您需要在(post_id, date).

您也可以使用JOIN:

select t.*
from t join
     (select t2.post_id, max(t2.date) as max_date
      from t t2
      where t2.date <= '2019-05-31'
      group by t2.post_id
     ) t2
     on t2.max_date = t.date
where t.status = 'public';

我希望相关子查询在正确的索引下具有更好的性能。然而,有时 MySQL 让我感到惊讶。

于 2019-06-29T11:12:14.520 回答
0

我们需要确定是否

  1. 每个的状态都post_idpublic月份之前May(带有 max(date) 的子查询),
  2. 任何在该月内post_id状态不等于的存在,publicMay
  3. 然后排除post_id满足的事情2。

因此,您可以使用:

select distinct t1.post_id
  from tab t1
where t1.post_id not in
    (
     select distinct t1.post_id
       from tab t1
       join
       (
        select post_id, max(date) as date
          from tab 
         where '2019-05-01'> date
         group by post_id ) t2
         on t1.post_id = t2.post_id 
      where t1.status != 'public' 
        and t1.date < '2019-06-01' 
        and t1.date > '2019-04-30'
);

+---------+
| POST_ID |
+---------+
|    2    |
+---------+

Demo

于 2019-06-29T03:46:57.450 回答