我要加入两个表,并且要排除第二个表中值大于1的任何结果。
在此示例中,我有一个名为movie_info
的表,其中包含有关电影的信息,每个电影都有唯一的ID。第二张名为crew_info
的表格具有每个电影摄制组的信息(具有电影的唯一ID),但是每个摄制组有多个条目,而不是每个电影有1个条目。看起来像这样:
+----------------------+
| movie_info |
+======================+
| id = '123' |
+----------------------+
+----------------------+
| crew_info |
+======================+
| id = '123' |
+----------------------+
| name = 'John' |
+----------------------+
| role = 'director' |
+----------------------+
+----------------------+
| crew_info |
+======================+
| id = '123' |
+----------------------+
| name = 'Mary' |
+----------------------+
| role = 'director' |
+----------------------+
+----------------------+
| crew_info |
+======================+
| id = '123' |
+----------------------+
| name = 'Sue' |
+----------------------+
| role = 'writer' |
+----------------------+
我像这样连接两个表:
SELECT a.id, b.*
FROM movie_info as a
LEFT JOIN crew_info as b
on a.id = b.id
到目前为止,这都是标准的。我要尝试做的只是返回 返回结果,其中crew_info
的计数只有1个导演。因此,像这样的独立查询:
SELECT id
FROM crew_info
WHERE role = 'director'
HAVING count(id) = 1
成功排除了像本例这样的结果,其中有1个以上的导演。但是,我如何将其与movie_info
表一起加入,以使它们全都在一个查询中?
很抱歉,如果不清楚。我对SQL比较陌生,因此请告诉我是否有我未正确表达的内容。谢谢。
编辑:抱歉,我忘记了另一件事!如果计数 大于1,如果匹配另一个值,如何仍包含结果?假设movie_info
还有一个名为sequel_id
的字段,只有在电影是续集的情况下才填写。我想排除导演数> 1且为空或为空的sequel_id
的结果,但 include 导演数> 1且结果为a的结果有效的sequel_id
值。我尝试了类似(HAVING COUNT(*) = 1 OR (HAVING COUNT(*) > 1 AND sequel_id IS NOT NULL))
的操作,但是出现语法错误。
答案 0 :(得分:1)
使用cte尝试以下操作
with cte as
(
SELECT id
FROM crew_info
WHERE role = 'director'
HAVING count(id) > 1
) select a.*,b.id FROM movie_info as a
LEFT JOIN cte as b
on a.id = b.id
没有cte,您还可以子查询
select a.*,b.id FROM movie_info as a
left join (
SELECT id
FROM crew_info
WHERE role = 'director'
group by id
HAVING count(id) > 1
) b on a.id=b.id
答案 1 :(得分:1)
只需将您现有的查询用作EXISTS子查询:
SELECT *
FROM movie_info
WHERE EXISTS (
SELECT 1
FROM crew_info
WHERE crew_info.id = movie_info.id
AND crew_info.role = 'director'
HAVING COUNT(*) = 1
)
OR sequel_id IS NOT NULL