2012-07-10 2 views
2

MySQ에서 쿼리 할 테이블이 3 개 있습니다. 다음과 같이여러 테이블, 여러 GROUP BY 및 group_concat에서 MySQL SELECT?

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

을 나는 모든 Items.Item ORDER BY를 각 플레이어 (Leaderboard.score DESC BY ORDER)를 선택하고 Actions.action LIKE는 '%를 먹었다'최신 액션을 선택하고 제공하는 질의를 필요로한다 시간 DESC는

그래서 예를 들어, 출력은 내가 다음과 같은 쿼리를 시도 지금까지

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

과 같을 것이다하지만 GROUP_CONCAT의 각 항목을 여러 번 돌려

,536,913,632 10
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

답변

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) ' –

+0

@ypercube : 고마워, 그 부분을 놓쳤다. – MvG

+0

이것은 정확히 요청대로 작동합니다. 많은 감사드립니다. 작업 테이블에서 여러 열을 어떻게 선택합니까? – user1491032