views:

26

answers:

2

Say, I have two tables like these:

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 |
                    +----+----------+------+----------+

And I want to select all groups and get the user with the highest rank (the highest number) for each group. So basically I want to get this result:

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

How has the select to be like? It maybe very simple, but I'm not getting it right now....

+2  A: 

Edit 2:

My previous answer was wrong, the max() call destroyed the result. Here's a correct solution:

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
)

The check in the WHERE clause should be more understandable, too.

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)
Cassy
Yes, that works - thanks so far! As long as there is no easier solution, this is my favorite ;-)
acme
With this solution you will get multiple rows if there are two people in the same group that have the same rank. If the rank is unique within a group, then there won't be a problem.
SorcyCat
+1  A: 
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
RedFilter