我试图为每个类别(model
表)只选择最高的千瓦(type
表)。
模型表
+-----+----+---------+
| id | kw | type_id |
+-----+----+---------+
| 1 | 2 | 1 |
| 2 | 5 | 1 |
| 3 | 10 | 2 |
| 4 | 4 | 2 |
| 5 | 5 | 2 |
| 6 | 4 | 3 |
| 7 | 3 | 4 |
| 8 | 7 | 5 |
+-----+----+---------+
类型表
+-----+----------+
| id | category |
+-----+----------+
| 1 | 1 |
| 2 | 1 |
| 3 | 2 |
| 4 | 2 |
| 5 | 2 |
+-----+----------+
尝试
一。此查询返回所有KW和类别的列表:
SELECT A.kw, B.category
FROM AC_MODEL A
INNER JOIN AC_TYPE B ON A.type_id = B.id
ORDER BY A.kw DESC
2.我试着做这样的事,但没用:
SELECT A.kw, B.category
FROM AC_MODEL A
INNER JOIN AC_TYPE B ON A.type_id = B.id
ORDER BY A.kw DESC
WHERE (A.kw, B.category) IN (
SELECT MAX(A.kw), B.category
FROM AC_MODEL A
INNER JOIN AC_TYPE B ON A.type_id = B.id
GROUP BY B.category
)
有人知道吗?
最佳答案
使用MAX
和GROUP BY
SELECT MAX(m.kw), t.category
FROM model m
INNER JOIN type t ON m.type_id = t.id
GROUP BY t.category
输出
MAX(m.kw) category
10 1
7 2
SQL小提琴:http://sqlfiddle.com/#!9/5d0df/5/0