我的db.movies中有5个表。像这样:
db.movies
id | title | plot
------------------
1 | matrix | ddd
db.aka
id | movie_id | aka_title | aka_country
----------------------------------------
1 | 1 | neo | usa
db.genre
id | genre_id | movie_id
------------------------
1 | 1 | 1
2 | 2 | 1
db.genre_name
id | genre_name
---------------
1 | sci-fi
2 | action
db.tags
id | movie_id | keyword
-----------------------
1 | 1 | hacker
2 | 1 | computer
如何创建这样的db.movies表:
db.movies
id | title | plot | genre | aka | aka_country | tags
1 | matrix | ddd | sci-fi, action | neo | usa | hacker, computer
我该怎么做?谢谢!
答案 0 :(得分:4)
您需要使用LEFT JOIN
:
select m.id,
m.title,
m.plot,
GROUP_CONCAT(distinct g.genre_name) as genre,
a.aka_title,
a.aka_country,
GROUP_CONCAT(distinct t.keyword) keyword
from movies m
left join aka a
on m.id = a.movie_id
left join genre g
on m.id =g.movie_id
left join genre_name gn
on g.genre_id = gn.id
left join tags t
on m.id = t.movie_id
group by m.id
我不知道你为什么要将这些数据存储在另一个表中,我猜你只是意味着结果不是表。如果任何表没有记录,LEFT JOIN
将允许返回记录。
答案 1 :(得分:1)
您可以使用:
select
mov.id,
mov.title,
mov.plot,
group_concat(distinct genre_name) as genre,
aka_title as aka,
aka_country,
group_concat(distinct keyword) as tags
from movies mov
join aka on mov.id = aka.movie_id
join genre gen on mov.id = gen.movie_id
join genre_name gna on gen.genre_id = gna.id
join tags tag on mov.id = tag.movie_id
group by mov.id;