多个内部联接或多个查询?

时间:2014-10-03 22:18:07

标签: mysql sql

我需要显示一个列出游戏标题,开发者和发布者的表格。每个游戏可以有多个开发者和发布者。从下图中,是否可以通过使用内部联接的一个查询获取所有这些信息,或者我是否必须进行多个数据库事务?

enter image description here

目前我已经能够获得一个游戏的开发者(单数),但我不确定如何在一个查询中抓住多个开发者以及多个发布者。这是我到目前为止的查询:

SELECT games.id, games.title, companies.id, companies.name
INNER JOIN game_developer ON game_developer.games_id = games.id
INNER JOIN companies ON companies.id = game_developer.companies_id
GROUP BY games.title
ORDER BY games.title
LIMIT 50

最终产品看起来应该是这样的:

enter image description here

1 个答案:

答案 0 :(得分:1)

使用GROUP_CONCAT获取所有名称:

SELECT games.id, games.title, 
        GROUP_CONCAT(DISTINCT dc.name) AS developers,
        GROUP_CONCAT(DISTINCT pc.name) AS publishers
INNER JOIN game_developer ON game_developer.games_id = games.id
INNER JOIN companies AS dc ON dc.id = game_developer.companies_id
INNER JOIN game_publisher AS gp ON gp.games_id = games.id
INNER JOIN companies AS dp ON dp.id = gp.companies_id
GROUP BY games.id
ORDER BY games.title
LIMIT 50

您需要使用DISTINCT,因为与发布商和开发者合作会生成包含大量重复项的交叉产品。