簡體   English   中英

MySQL SELECT來自多個表,多個GROUP BY和group_concat?

[英]MySQL SELECT from multiple tables, multiple GROUP BY and group_concat?

我有三個表,我想在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中多次返回每個Item

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

任何幫助非常感謝!

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中驗證。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM