mysql查询必须如何实现显示的结果?

时间:2010-01-22 14:34:34

标签: mysql group-by aggregate

说,我有两个这样的表:

Table group         Table user
+----+-----------+  +----+----------+------+----------+
| id | groupname |  | id | username | rank | group_id |
+----+-----------+  +----+----------+------+----------+
|  1 | Friends   |  |  1 | Frank    |    1 |        1 |
|  2 | Family    |  |  2 | Mike     |    3 |        1 |
+----+-----------+  |  3 | Steve    |    2 |        1 |
                    |  4 | Tom      |    1 |        2 |
                    +----+----------+------+----------+

我想选择所有组并获得每个组的最高级别(最高编号)的用户。所以基本上我想得到这个结果:

+-----------------+----------+---------+---------------+    
| group.groupname | group.id | user.id | user.username |
+-----------------+----------+---------+---------------+
| Friends         |        1 |       2 |         Mike  |
| Family          |        2 |       4 |          Tom  |
+-----------------+----------+---------+---------------+    

选择如何? 它可能很简单,但我现在没有得到它......

2 个答案:

答案 0 :(得分:3)

编辑2:

我之前的回答是错误的,max()调用破坏了结果。这是一个正确的解决方案:

SELECT g.groupname, g.id AS group_id, u.id AS user_id, u.username
FROM `user` u
LEFT JOIN `group` g ON (u.group_id=g.id)
WHERE u.rank=(
    SELECT MAX(rank) 
    FROM `user` u2 
    WHERE u.group_id=u2.group_id
)

WHERE子句中的检查也应该更容易理解。

mysql> SELECT g.groupname, g.id AS group_id, u.id AS user_id, u.username
    -> FROM `user` u
    -> LEFT JOIN `group` g ON (u.group_id=g.id)
    -> WHERE u.rank=(
    ->     SELECT MAX(rank)
    ->     FROM `user` u2
    ->     WHERE u.group_id=u2.group_id
    -> );
+-----------+----------+---------+----------+
| groupname | group_id | user_id | username |
+-----------+----------+---------+----------+
| Friends   |        1 |       2 | Mike     |
| Family    |        2 |       4 | Tom      |
+-----------+----------+---------+----------+
2 rows in set (0.00 sec)

答案 1 :(得分:2)

select g.groupname, u.group_id, u.id as user_id, u.username
from group g
inner join (
    select group_id, max(rank) as MaxRank
    from user
    group by group_id
) um on g.id = um.group_id
inner join user u on um.group_id = u.group_id and um.MaxRank = u.rank