T有下表:
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
我想找到每个中间价格最低的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
答案 0 :(得分:1)
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
答案 1 :(得分:0)
尝试:http://www.sqlfiddle.com/#!2/e2244c/71
SELECT t1.mid, MIN(DISTINCT t1.pid) AS Expr1
FROM tableName as t1
INNER JOIN
tableName AS tableName_1 ON t1.mid = tableName_1.mid
GROUP BY t1.mid
ORDER BY MIN(DISTINCT t1.pid) DESC
答案 2 :(得分:0)
试试这个:
select t1.*
from tablename t1
inner join (select mid, min(pid) min_pid from
(select t1.mid,t1.pid
FROM tablename t1
inner join (select mid,
min(price) as min_price
FROM tablename
GROUP BY mid) t2 on t1.mid = t2.mid
and t1.price = t2.min_price) t
group by mid) t2 on t1.mid = t2.mid
and t1.pid = t2.min_pid
;
它以最低价格和最小pid生成行。
答案 3 :(得分:-1)
它起作用:
SELECT t1.mid,t1.pid FROM tableName t1
INNER JOIN (
SELECT mid AS mid1, pid AS pid1, min(price) as min_price FROM tableName GROUP BY mid
) as t2
on t1.mid = t2.mid1 and t1.price = t2.min_price and t1.pid = t2.pid1;