簡體   English   中英

MySQL:僅在最接近日期具有列值的地方選擇行

[英]MySQL: select row only where closest to date has column value

我想返回所有在5月(2019-05)公開的行,因此,如果在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月底之前的最后狀態更改已public

5月底之前將post_id 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使我感到驚訝。

我們需要確定是否

  1. 每個post_id的狀態在May (具有max(date)的子查詢)之前是public
  2. May內,任何post_id存在且狀態不等於public
  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    |
+---------+

演示

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM