2010-01-22 41 views
2

說,我有兩個表像這樣:mysql查詢如何才能達到所示結果?

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

選擇如何是像? 它也許很簡單,但我沒有得到它現在....

+0

編輯的結果,使組名被選中,否則對用戶表的簡單查詢會做的伎倆 – acme 2010-01-22 14:51:53

回答

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

是的,這工程 - 感謝這麼遠!只要沒有更簡單的解決方案,這是我的最愛;-) – acme 2010-01-22 14:53:47

+0

使用此解決方案,如果同一組中具有相同級別的兩個人,則您將獲得多行。如果排名在一個組中是唯一的,那麼就不會有問題。 – SorcyCat 2010-01-22 15:21:17