簡體   English   中英

為評估為真的 IN 條件元素設置限制

[英]Set limit for IN condition element that evaluate true

table: t
+--------------+-----------+-----------+
| Id           | price     | Date      |
+--------------+-----------+-----------+
|  1           | 30        | 2021-05-09|
|  1           | 24        | 2021-04-26|
|  1           | 33        | 2021-04-13|
|  2           | 36        | 2021-04-18|
|  3           | 15        | 2021-04-04| 
|  3           | 33        | 2021-05-06|
|  4           | 46        | 2021-02-16|
+--------------+-----------+-----------+

我想 select 行,其中 id 為 1,2,4,並按日期降序獲取每個 id 的最大 2 行。

+--------------+-----------+-----------+
| Id           | price     | Date      |
+--------------+-----------+-----------+
|  1           | 30        | 2021-05-09|
|  1           | 24        | 2021-04-26|
|  2           | 36        | 2021-04-18|
|  4           | 46        | 2021-02-16|
+--------------+-----------+-----------+

就像是:

Select * from t where Id IN ('1','2','4') limit 2 order by Date desc; 

這將限制獲取的整體結果。

使用row_number()

select id, price, date
from (select t.*,
             row_number() over (partition by id order by date desc) as seqnum
      from t
      where id in (1, 2, 4)
     ) t
where seqnum <= 2;

可能最有效的方法是相關子查詢:

select t.*
from t
where t.id in (1, 2, 4) and
      t.date >= coalesce( (select t2.date
                           from t t2
                           where t2.id = t.id
                           order by t2.date desc
                           limit 1,1
                           ), t.date
                        );

為了提高性能,您需要(id, date)上的索引。 此外,如果在同一日期給定 id 有多行,這可能會返回重復項。

是一個 db<>fiddle。

暫無
暫無

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

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