views:

47

answers:

4

Hello,

I have 3 tables;

game, platform, game_platform

game

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

platform

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

game_platform

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

What I want is to get a row conatining data from game table and also all the platforms for that game.

However with a regular query I get multiple rows for games with more than one platform. Is there a way to get them on a single row?

Thanks ...

+2  A: 
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

If you want to dynamically determine the platform columns, then you need to build the query dynamically in your calling or middle-tier code.

Thomas
since the number of platform columns can change Martin Smith's method works better for me. However it seems that this type of query works faster than his. But it seems this type query will be useful for me in the future. Thanks
Sinan
@Sinan - Np, although the two solutions produce different results. Martin's gives you a delimited list of values. Mine gives you a column for each platform. If all you want is list, then Martin's is better. If you wanted to use the results in grid with a column for each platform or another query, then a dynamically generated version of my query might be better.
Thomas
+2  A: 

You don't provide an example of desired output. If you want all the platforms brought back in one column this will do it.

   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
Martin Smith
A: 

There is a mysql concat function.

http://www.brainbell.com/tutorials/MySQL/Concatenating_Fields.htm

Judas Imam
GROUP_CONCAT() is more suitable for this purpose (I think)
Sinan