los*_*1in 6 mysql greatest-n-per-group rank
所以,我有类似的表:
sn color value
1 red 4
2 red 8
3 green 5
4 red 2
5 green 4
6 green 3
Run Code Online (Sandbox Code Playgroud)
现在我需要每种颜色的最新 2 行,例如:
2 red 8
4 red 2
5 green 4
6 green 3
Run Code Online (Sandbox Code Playgroud)
除了对每种颜色使用单独的查询之外,该怎么做?
谢谢
这是“每组最大 n 个”问题的变体。LATERAL
它可以与窗口函数或连接(也称为)一起使用CROSS/OUTER APPLY
,只要 MySQL 实现了它们*。
这是一种有效的方法。我称之为“穷人的十字架应用”:
select t.*
from
( select distinct color from tbl ) as td -- for every colour
left join -- join to the table
tbl as t -- and get all rows
on t.color = td.color -- with that color
and t.sn >= coalesce( -- and sn bigger or equal than
( select ti.sn -- the 2nd higher sn value
from tbl as ti
where ti.color = td.color
order by ti.sn desc
limit 1 offset 1 -- 1 + 1st = 2nd
), -9223372036854775808 -- the smallest possible bigint value,
) ; -- to cover cases of colours
-- with a single appearance, where
-- the subquery returns NULL
Run Code Online (Sandbox Code Playgroud)
在dbfiddle.uk进行测试。此查询将使用(color, sn)
或上的索引。(color, sn, value)
如果只有几个不同的color
值,则非常有效。
*:MariaDB,MySQL 的一个分支,确实实现了窗口函数,因此具有排序函数的解决方案,如ROW_NUMBER()
、RANK()
或DENSE_RANK()
可以在那里工作。
归档时间: |
|
查看次数: |
13406 次 |
最近记录: |