如何查询可能不存在的多对多?

时间:2016-10-17 02:15:08

标签: mysql

说我有这些表和值

table actors
id  int  11  primary key auto_increment
name  varchar  30

table movies
id  int  11  primary key auto_increment
name  varchar  30

table actors_movies
actor_id  int  11
movie_id  int  11

我如何查询数据库以获取他们所在的所有演员和电影?

例如,像这样:

从......(QUERY)....中选择actors.name,movies.name。

输出就像这样

actors.name movies.name movies.name movies.name
Bob         Movie A     NULL        NULL
Melissa     Movie A     Movie B     NULL
Rick        NULL        NULL        Movie C

2 个答案:

答案 0 :(得分:2)

逗号分隔:

SELECT actors.name, GROUP_CONCAT(movies.name)
FROM actors_movies
LEFT JOIN actors ON actors.id = actors_movies.actor_id
LEFT JOIN movies ON movies.id = actors_movies.movie_id
GROUP BY actors_movies.actor_id

输出将是这样的:

+-------------+---------------------------+
| name        | GROUP_CONCAT(movies.name) |
+-------------+---------------------------+
| Bob         | Movie A                   |
| Melissa     | Movie A,Movie B           |
| Rick        | Movie C                   |
+-------------+---------------------------+

SQLFiddle:http://sqlfiddle.com/#!9/04c0a2/1

答案 1 :(得分:0)

假设您需要单独的列,这里有一个使用conditional aggregation cross joinouter join的选项:

select a.name, 
       max(case when am.movie_id = 1 then m.name end) movie1,
       max(case when am.movie_id = 2 then m.name end) movie2,
       max(case when am.movie_id = 3 then m.name end) movie3
from actors a cross join movies m 
     left join actors_movies am on a.id = am.actor_id and m.id = am.movie_id
group by a.id, a.name