如何为单行选择多个结果 - MySQL

时间:2010-06-26 20:54:57

标签: sql mysql

我有3个表:gameplatformgame_platform

游戏:

id    name               desc
----  ------------       ---------
1     Modern Warfare...  Awesome game......
2     ...                ...
3     ...                ...

平台:

id    name
----  ------------
1     pc
2     ps3
3     ...

game_platform:

game_id    platform_id
--------   -----------
1          1
1          2
...        ...

我想要的是获取一行包含游戏桌中的数据以及该游戏的所有平台。

然而,对于常规查询,我会为具有多个平台的游戏获得多行。有没有办法把它们放在一排?

3 个答案:

答案 0 :(得分:4)

您没有提供所需输出的示例。如果您希望将所有平台带回一列,那么就可以实现。

   SELECT g.id, g.name, g.desc, GROUP_CONCAT(P.name) AS platforms
    from game g
    JOIN game_platform gp ON gp.game_id = g.id
    JOIN platform P ON gp.platform_id = p.id
    GROUP BY g.id, g.name, g.desc

答案 1 :(得分:2)

Select G.Id, G.name
    , Min( Case When P.Id = 1 Then P.Name End ) As Platform1
    , Min( Case When P.Id = 2 Then P.Name End ) As Platform2
    , Min( Case When P.Id = 3 Then P.Name End ) As Platform3
From game As G
    Join game_platform As GP
        On GP.game_id = G.id
    Join platform As P
        On P.Id = GP.platform_id
Group By G.Id, G.name

如果要动态确定平台列,则需要在调用或中间层代码中动态构建查询。

答案 2 :(得分:0)