简体   繁体   English

重用相关子查询的结果

[英]Reuse result of a correlated subquery

I have a table media_tags containing two columns linking media to user defined tags. 我有一个表media_tags其中包含将媒体链接到用户定义的标签的两列。 I want to do some queries selecting media with complicated conditions on the tags. 我想进行一些查询,以选择标签上条件复杂的媒体。 My current solution is using the same correlated subquery multiple times. 我当前的解决方案是多次使用相同的相关子查询。

Multiple SO answers have pointed me to CTEs but as far as i understand it those can only be used to replace uncorrelated subqueries. 多个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));

How about using not exists ? 使用not exists怎么样?

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)
                 );

You can do a self join, GROUP BY media_id and set the conditions in the HAVING clause: 您可以使用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

or even simpler without the self join check if this works also: 如果没有自连接,甚至更简单,请检查是否也可以:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM