4

MySQでクエリしたいテーブルが3つあります。次のように:

**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 BYTimeDESCを指定するクエリが必要です。

たとえば、出力は次のようになります

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

どんな助けでも大歓迎です!

4

1 に答える 1

8
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

結果はSQLFiddleで検証されまし

于 2012-07-10T14:22:00.770 に答える