我试图为每个类别(model
表格)选择最高的 kw (type
表格)。< / p>
模型表
+-----+----+---------+
| 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 |
+-----+----------+
尝试
1.此查询返回所有 kws 和类别的列表:
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。我试图做这样的事情answer,但它不起作用:
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
)
有人有想法吗?
答案 0 :(得分:2)
使用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 FIDDLE:http://sqlfiddle.com/#!9/5d0df/5/0