表的条件sql查询

时间:2012-09-16 11:41:52

标签: php mysql sql sql-server database

我必须从SQL运行查询。也许太容易或不容易,但不幸的是我不懂SQL。所以这是我的表格:

id | movie_name
------------
1  | prometheus

名称

id | person_name
-----------------
1  | Ridley Scott
2  | Noomi Rapace
3  | Michael Fassbender
4  | Charlize Theron
5  | Damon Lindelof

films_cast

id | film_id | person_id | type
-------------------------------
1  | 1       | 1         | director
2  | 1       | 2         | actor
3  | 1       | 3         | actor
4  | 1       | 4         | actor
5  | 1       | 5         | writer

我怎样才能从这些表中得出这样的结论:

film_archive

id | movie_name | director     | writer         | cast
---------------------------------------------------------------------------------------
1  | prometheus | Ridley Scott | Damon Lindelof | Noomi Rapace, Michael Fassbender, Charlize Theron

谢谢!

3 个答案:

答案 0 :(得分:6)

您需要join您的表格,然后在给定合适条件的情况下,在名称列上按电影执行GROUP_CONCAT()聚合分组:

SELECT   f.id,
         f.movie_name,
         GROUP_CONCAT(IF(c.type='director', n.person_name, NULL)) AS director,
         GROUP_CONCAT(IF(c.type='writer',   n.person_name, NULL)) AS writer,
         GROUP_CONCAT(IF(c.type='actor',    n.person_name, NULL)) AS cast
FROM     films f LEFT JOIN films_cast c ON c.film_id   = f.id
                 LEFT JOIN names n      ON c.person_id = n.id
GROUP BY f.id

sqlfiddle上查看。

答案 1 :(得分:2)

由于你的问题也有sql-server标签,不幸的是sql-server没有GROUP_CONCAT,需要FOR XML / STUFF之类的替代方案:

SELECT f.id, f.movie_name,
       STUFF((SELECT ',' + p.person_name
              FROM persons p 
                INNER JOIN films_cast fc on fc.person_id = p.id
                WHERE fc.film_id = f.id AND fc.type = 'director'
              FOR XML PATH (''))
             , 1, 1, '') AS director,
        STUFF((SELECT ',' + p.person_name
              FROM persons p 
                INNER JOIN films_cast fc on fc.person_id = p.id
                WHERE fc.film_id = f.id AND fc.type = 'writer'
              FOR XML PATH (''))
             , 1, 1, '') AS writer,
        STUFF((SELECT ',' + p.person_name
              FROM persons p 
                INNER JOIN films_cast fc on fc.person_id = p.id
                WHERE fc.film_id = f.id AND fc.type = 'actor'
              FOR XML PATH (''))
             , 1, 1, '') AS cast
    FROM films f;

SQLFiddle here

答案 2 :(得分:1)

试试这个,

SELECT      a.id, a.movie_name,
            GROUP_CONCAT((CASE WHEN b.type = 'director' THEN c.person_name ELSE NULL END)) as `director`,
            GROUP_CONCAT((CASE WHEN b.type = 'writer' THEN c.person_name ELSE NULL END)) as `writer`,
            GROUP_CONCAT((CASE WHEN b.type = 'actor' THEN c.person_name ELSE NULL END)) as `cast`
FROM        films a
            LEFT JOIN film_cast b
                ON a.id = b.film_id
            LEFT JOIN names c
                ON b.person_id = c.id
GROUP BY    a.id, a.movie_name

SQLFiddle Demo