mysql - 根据另一个表中另一列的最大值选择唯一列

时间:2015-06-08 10:41:55

标签: mysql sql database join

我试图为每个类别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
)

有人有想法吗?

1 个答案:

答案 0 :(得分:2)

使用MAXGROUP 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