gpt4 book ai didi

mysql - 在 mysql 中进行分组时只选择一行

转载 作者:行者123 更新时间:2023-11-29 03:22:38 25 4
gpt4 key购买 nike

有下表:

mid pid   price
1 100 10
1 200 10
1 300 10
1 400 10
2 500 20
2 600 30
2 700 20
3 800 40
3 900 50

我想为每个 mid 找到价格最低的 pid。

为此我正在查询这段代码。

SELECT t1.mid,t1.pid 
FROM tableName t1
JOIN (
SELECT mid, min(price) as min_price
FROM tableName
GROUP BY mid
) as t2 on t1.mid = t2.mid and t1.price = t2.min_price;

理想情况下它应该给出结果,但在我的例子中,每个组中都有多个具有相同价格的 pid。所以它正在打印所有结果。

但我只想为每个中间限制 1 行。

有什么办法吗?我有一个 sqlfiddle demo

最佳答案

select s.mid,s.pid,s.price
from
(
SELECT t1.mid,t1.pid,t1.price,
if (t1.mid <> @p, @rn:=1,@rn:=@rn+1) rn,
@p:=t1.mid p
FROM (select @rn:=0,@p:=0) rn,t t1
order by t1.mid,t1.price,t1.pid
) s where s.rn = 1

关于mysql - 在 mysql 中进行分组时只选择一行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41358688/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com