0

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

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

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

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

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

音乐
ID TITLE
10 音乐总监

董事
ID TITLE
10 董事

视频
ID TITLE
20 SomeVideo

4

2 回答 2

0

要将演员名称组合成一个逗号分隔的列表,您可以使用 mysqlGROUP_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
于 2013-01-05T21:54:32.247 回答
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;
于 2013-01-05T22:47:19.353 回答