用内连接连接结果

时间:2014-01-23 07:48:39

标签: mysql

我写这篇SQL以获得与人物合作的电影(role_id = 1 - 是导演)。虽然电影有单个导演 - 一切都很好,但是当有多个导演时,会出现具有相同电影名称的额外行。

SELECT
    m.name, 
    ps.name as director
FROM
    movies m
INNER JOIN participants p ON
    m.movie_id = p.movie_id
INNER JOIN persones ps ON
    ps.person_id = p.person_id AND
    p.role_id = 1    
ORDER BY m.updated_at DESC
LIMIT 10\G

例如

*************************** 1. row ***************************
    name: Film1
director: director1
*************************** 2. row ***************************
    name: Film1
director: director2
*************************** 3. row ***************************
    name: Film1
director: director3
*************************** 4. row ***************************
    name: Film2
director: director4
*************************** 5. row ***************************
    name: Film2
director: director5
*************************** 6. row ***************************
    name: Film2
director: director6

好的,我在单行

中找到了连接控制器的group_concat
SELECT
    m.name, 
    GROUP_CONCAT(ps.name SEPARATOR ", ") as director
FROM
    movies m
INNER JOIN participants p ON
    m.movie_id = p.movie_id
INNER JOIN persones ps ON
    ps.person_id = p.person_id AND
    p.role_id = 1    
ORDER BY m.updated_at DESC
LIMIT 10\G

但我有意想不到的结果!

*************************** 1. row ***************************
    name: Film123
director: director1, someperson1, someperson3, ......, someperson18

与来自其他类别(艺术家或smth)的人只有一行。甚至包含电影的行的名称与 ORDER BY m.updated_at DESC 必须返回的名称不一样

2 个答案:

答案 0 :(得分:1)

您缺少GROUP BY使用群组功能但未对其进行分组

SELECT
    m.name, 
    GROUP_CONCAT(ps.name SEPARATOR ", ") as director
FROM
    movies m
INNER JOIN participants p ON
    m.movie_id = p.movie_id
INNER JOIN persones ps ON
    ps.person_id = p.person_id AND
    p.role_id = 1    
GROUP BY m.name /* or you can use the movie id column here*/
ORDER BY m.updated_at DESC
LIMIT 10

GROUP_CONCAT(expr)

GROUP BY (Aggregate) Functions

编辑还要确保movie_id表格中有movies

SELECT
    m.movie_id ,
    m.international_name AS o_name,
    m.description AS description,
    m.name AS name,
    m.covers AS covers,
    m.YEAR AS YEAR,
    m.updated_at AS added,
    GROUP_CONCAT(ps.name SEPARATOR ', ') AS director
FROM
    movies AS m
INNER JOIN  movies_genres AS mgen ON
    (m.movie_id = mgen.movie_id)
INNER JOIN participants p ON
    m.movie_id = p.movie_id
INNER JOIN persones ps ON
    ps.person_id = p.person_id AND
    p.role_id = 1 /* Directors */
WHERE
    m.hidden=0 AND
    mgen.genre_id = 6 AND

GROUP BY m.name
ORDER BY m.updated_at DESC

答案 1 :(得分:0)

如果您正在使用GROUP_CONCAT,则必须使用GROUP BY来创建组。

SELECT
m.name, 
GROUP_CONCAT(ps.name SEPARATOR ", ") as director
FROM
    movies m
INNER JOIN participants p ON
    m.movie_id = p.movie_id
INNER JOIN persones ps ON
    ps.person_id = p.person_id AND
    p.role_id = 1    
GROUP BY m.movie_id,m.name
ORDER BY m.updated_at DESC
LIMIT 10