使用join从两个表中选择多个条目

时间:2013-01-05 20:47:06

标签: mysql

我想生成一个结果,该结果将从下面给出的数据库中提供以下结果。

20  'someVideo'  'Jason Statham, Tom Cruise, Bruce Wills, Anne Hathaway'  'musicDirector'  'Director

请注意,演员用“,”分开。提前致谢

term_relationships
ID video_id related_id type
1 20 5演员
1 20 2演员
1 20 3演员
1 20 4演员
1 20 10音乐
1 20 11导演

演员
ID TITLE
2汤姆克鲁斯
3布鲁斯威尔斯 4安妮海瑟薇
5 Jason Statham

音乐
ID TITLE
10 musicDirector

导演
ID TITLE
10主任


ID TITLE
20 SomeVideo

2 个答案:

答案 0 :(得分:0)

要将actor名称组合成逗号分隔列表,可以使用mysql GROUP_CONCAT函数。检查此SQL语句是否能满足您的需求:

Select tr.video_id, videos.title AS video, 
   GROUP_CONCAT(DISTINCT(actors.title) SEPARATOR ',') AS actor_names,  
   GROUP_CONCAT(DISTINCT(directors.title) SEPARATOR ',') AS director,   
   GROUP_CONCAT(DISTINCT(musics.title) SEPARATOR ',') AS music 
FROM term_relationships tr inner join videos on videos.id = tr.video_id 
LEFT JOIN actors on tr.related_id = actors.id 
LEFT JOIN musics on tr.related_id = musics.id and tr.type = 'music' 
LEFT JOIN directors on tr.related_id = directors.id and tr.type = 'director' 
WHERE tr.video_id = 20 GROUP BY tr.video_id

答案 1 :(得分:0)

Andrea对GROUP_CONCAT功能的回答很棒并且有效。但是,它应该通过为这样的演员添加类型过滤器来完善:

select tr.video_id, v.title, 
  GROUP_CONCAT(DISTINCT(a.title) SEPARATOR ',') actors,
  GROUP_CONCAT(DISTINCT(d.title) SEPARATOR ',') director,
  GROUP_CONCAT(DISTINCT(m.title) SEPARATOR ',') music
FROM term_relationships tr 
  INNER JOIN videos v on v.id = tr.video_id 
  LEFT JOIN actors a on tr.related_id = a.id and tr.type = 'actor'
  LEFT JOIN musics m on tr.related_id = m.id and tr.type = 'music' 
  LEFT JOIN directors d on tr.related_id = d.id and tr.type = 'director' 
WHERE tr.video_id = 20 
GROUP BY tr.video_id;