我有一个表media_tags
,其中包含两列,将媒体链接到用户定义的标签。我想进行一些查询,以选择标签上条件复杂的媒体。我当前的解决方案是多次使用相同的相关子查询。
多个SO答案将我引向了CTE,但据我所知,这些只能用于替换不相关的子查询。
SELECT outer.media_id
FROM media_tags AS outer
WHERE 1 IN (SELECT tag_id FROM media_tags AS inner WHERE outer.media_id = inner.media_id)
AND 2 NOT IN (SELECT tag_id FROM media_tags AS inner WHERE outer.media_id = inner.media_id)
AND (3 IN (SELECT tag_id FROM media_tags AS inner WHERE outer.media_id = inner.media_id)
OR 4 IN (SELECT tag_id FROM media_tags AS inner WHERE outer.media_id = inner.media_id));
答案 0 :(得分:0)
如何使用SELECT m2.media_id
FROM media_tags mt
WHERE NOT EXISTS (SELECT tag_id
FROM media_tags mt2
WHERE mt2.media_id = mt.media_id AND
mt2.tag_id IN (1, 2, 3, 4)
);
?
{{1}}
答案 1 :(得分:0)
您可以进行自联接GROUP BY media_id
并在HAVING
子句中设置条件:
SELECT outer.media_id
FROM media_tags AS outer INNER JOIN media_tags AS inner
ON outer.media_id = inner.media_id
GROUP BY outer.media_id
HAVING
SUM(inner.tag_id = 1) > 0
AND
SUM(inner.tag_id = 2) = 0
AND
SUM(inner.tag_id IN (3, 4)) > 0
甚至更简单,如果没有自连接,也可以检查是否可行:
SELECT media_id
FROM media_tags
GROUP BY media_id
HAVING
SUM(tag_id = 1) > 0
AND
SUM(tag_id = 2) = 0
AND
SUM(tag_id IN (3, 4)) > 0