对于这张桌子......
id type food price
--------------------------
1 veg carrot 10
2 veg turnip 11
3 fruit bramble 6
4 fruit rasp 4
5 fruit current 9
...
我可以为每种食物类型返回最贵的食物的最高价格......
select max(price) from tableName group by type;
但我想返回包含每种食物类型最贵食物的每行的id号。并且每种食物类型返回一行且仅一行。就是回来......
id
----
2
5
...
这是我真正问题的简化版。
答案 0 :(得分:1)
SELECT id
FROM ( SELECT id, type
FROM table
ORDER BY price DESC) AS h
GROUP BY type
答案 1 :(得分:0)
SELECT max(id) from
(SELECT t1.* FROM tableName t1
JOIN (SELECT type, max(price) AS price FROM tableName GROUP BY type) t2
ON t2.type = t1.type AND t2.price = t1.price) t3
GROUP BY userId;
答案 2 :(得分:0)
当更多的食物具有相同的类型和价格时,这个可怕的查询将起作用 我几乎不会在生产中使用它,因为这是不可维护的。
SELECT MIN(id) AS id
FROM (
SELECT t.id AS id, t.type
FROM tableName t
JOIN (
SELECT MAX(price) AS m, type
FROM tableName
GROUP BY type
) sub
ON sub.m=t.price AND sub.type=t.type
ORDER BY id
) whatever
GROUP BY type