表的条件sql查询
Posted
技术标签:
【中文标题】表的条件sql查询【英文标题】:conditional sql query for tables 【发布时间】:2012-09-08 22:05:00 【问题描述】:我必须从 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
谢谢!
【问题讨论】:
【参考方案1】:您需要 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 上查看。
【讨论】:
你做的比我快得多! 如何将此结果导出为 CSV/TXT 文件? @jeangrey:在FROM
子句之前,添加INTO OUTFILE '/path/to/file.csv' FIELDS TERMINATED BY ',' OPTIONALLY ENCLOSED BY '"'
。【参考方案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
【讨论】:
【参考方案3】:试试这个,
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
【讨论】:
以上是关于表的条件sql查询的主要内容,如果未能解决你的问题,请参考以下文章
SQL语句 一个表的值与另一个表的字段一致,怎么把两一个表的值作为条件,限定查询的字段