-3

我的 db.movi​​es 中有 5 个表。像这样:

db.movi​​es

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.movi​​es 表:

db.movi​​es

id | title   | plot | genre          | aka | aka_country | tags
1  | matrix  | ddd  | sci-fi, action | neo | usa         | hacker, computer

我怎样才能做到这一点?谢谢!

4

2 回答 2

4

您将要为此使用 a 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将允许返回记录。

SQL Fiddle with Demo

于 2012-09-13T21:47:18.490 回答
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;

sqlfiddle

于 2012-09-13T21:41:56.950 回答