MySQL SELECT 从多个表,多个 GROUP BY 和 group_concat?
Posted
技术标签:
【中文标题】MySQL SELECT 从多个表,多个 GROUP BY 和 group_concat?【英文标题】:MySQL SELECT from multiple tables, multiple GROUP BY and group_concat? 【发布时间】:2012-07-10 01:05:56 【问题描述】:我想在 MySQ 中查询三个表。如下:
**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)并选择他们最新的 Action WHERE Actions.action LIKE 'Ate %',然后给出所有 Items.Item ORDER BY Time DESC
例如,输出将如下所示
**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
非常感谢任何帮助!
【问题讨论】:
您无法使用子查询对结果进行排序:外部GROUP BY
将覆盖目前存在的任何排序。
【参考方案1】:
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 中验证。
【讨论】:
制作:GROUP_CONCAT(Items.Item SEPARATOR ', ' ORDER BY Items.Time DESC)
@ypercube:谢谢,错过了那部分。
这完全按照要求工作,非常感谢。如何从 Actions 表中选择多个列?
@user1491032:讨论这个问题将超出此类评论的范围,特别是在源代码格式化功能方面。最好问一个关于这个的后续问题。以上是关于MySQL SELECT 从多个表,多个 GROUP BY 和 group_concat?的主要内容,如果未能解决你的问题,请参考以下文章
在 PHP 中使用多个条件访问嵌套的 MySQL Select。