2012-07-10 86 views
2

我有三个表,我想在MySQ中查询。具体如下:MySQL从多个表中选择多个GROUP BY和group_concat?

**Table: Leaderboard** 
Name | Score 
------------ 
James | 1 
Steve | 2 
Dave | 5 

**Table: Actions** 
Name | Action  | Time 
---------------------------- 
James | Ate an apple | 01:00 
James | Kicked a dog | 02:00 
Steve | Ate a dog | 03:00 
Steve | Kicked a hen | 01:00 
Dave | died   | 02:00 

**Table: Items** 
Name | Item   | Time 
---------------------------- 
James | Chainsaw  | 01:00 
James | Hammer  | 01:05 
James | Crowbar  | 01:10 
Steve | Hammer  | 02:00 
Steve | Egg   | 01:05 
Dave | Egg   | 01:05 

我需要它选择每个玩家(ORDER BY Leaderboard.score DESC),并选择WHERE Actions.action LIKE '%吃' 自己的最新动作,然后给所有Items.Item ORDER BY查询时间倒序

因此,举例来说,输出应该是这样的

**Output** 
Name | Latest_Action | Items 
Steve | Ate a dog  | Hammer, Egg 
James | Ate an apple | Crowbar, Hammer, Chainsaw 

到目前为止,我曾尝试以下查询,但它多次返回每个项目在GROUP_CONCAT

SELECT Leaderboard.Name, Actions.*, group_concat(Items.Item) 
FROM Leaderboard, Actions, Items 
WHERE Items.Name = Actions.Name 
    AND Actions.Action LIKE 'Ate %' 
    AND Actions.Name IN (SELECT Name FROM Leaderboard ORDER BY SCORE DESC) 
GROUP BY Leaderboard.name 

任何帮助非常感谢!

+0

您使用子查询对结果进行排序将不起作用:外面的GROUP BY将覆盖到目前为止存在的任何排序。 – MvG 2012-07-10 14:26:31

回答

6
SELECT Leaderboard.Name, 
    (SELECT Actions.Action 
    FROM Actions 
    WHERE Actions.Name = Leaderboard.Name 
    AND Actions.Action LIKE 'Ate%' 
    ORDER BY Time DESC 
    LIMIT 1 
) AS Latest_Action, 
    GROUP_CONCAT(Items.Item 
       ORDER BY Items.Time DESC 
       SEPARATOR ', ' 
      ) AS Items 
FROM Leaderboard 
    LEFT JOIN Items ON Leaderboard.Name = Items.Name 
GROUP BY Leaderboard.Name 
HAVING Latest_Action IS NOT NULL 
ORDER BY Leaderboard.Score DESC 

结果在SQL Fiddle中被验证。

+0

做到这一点:'GROUP_CONCAT(Items.Item SEPARATOR','ORDER BY Items.Time DESC)' – 2012-07-10 14:28:06

+0

@ypercube:谢谢,错过了那部分。 – MvG 2012-07-10 14:30:09

+0

这完全按照要求工作,非常感谢。 我将如何从动作表中选择多个列? – user1491032 2012-07-10 14:59:52