8

Every now and then I see these being used, but it never seems to be anything that can't be performed as equally well, if not better, by using a normal join or subquery.

I see them as being misleading (they're arguably harder to accurately visualize compared to conventional joins and subqueries), often misunderstood (e.g. using SELECT * will behave the same as SELECT 1 in the EXISTS/NOT EXISTS subquery), and from my limited experience, slower to execute.

Can someone describe and/or provide me an example where they are best suited or where there is no option other than to use them? Note that since their execution and performance are likely platform dependent, I'm particularly interested in their use in MySQL.

4

3 回答 3

4

我时不时地看到这些被使用,但它似乎从来没有通过使用普通的连接或子查询来表现得同样好,如果不是更好的话。

这篇文章(虽然SQL Server相关):

您可能会感兴趣。

简而言之,JOIN是集合操作,whileEXISTS是谓词。

换句话说,这些查询:

SELECT  *
FROM    a
JOIN    b
ON      some_condition(a, b)

对比

SELECT  *
FROM    a
WHERE   EXISTS
        (
        SELECT  NULL
        FROM    b
        WHERE   some_condition(a, b)
        )

不一样:前者可以从 中返回多个记录a,而后者不能。

它们的对应物NOT EXISTSvs.LEFT JOIN / IS NULL在逻辑上是相同的,但在性能方面却不同。

事实上,前者在以下方面可能更有效SQL Server

于 2010-12-20T17:59:51.057 回答
1

您不能[轻松]在UPDATE语句中使用连接,因此WHERE EXISTS在那里工作得很好:

UPDATE mytable t
   SET columnX = 'SomeValue'
 WHERE EXISTS 
   (SELECT 1 
      FROM myothertable ot
     WHERE ot.columnA = t.columnY
       AND ot.columnB = 'XYX'
   );

编辑:基于 Oracle 而不是 MySQL,是的,有一些方法可以使用内联视图来实现,但恕我直言,这更干净。

于 2010-12-16T23:38:31.323 回答
1

如果主查询返回的行数少于您要查找它们的表。例子:

SELECT st.State
FROM states st
WHERE st.State LIKE 'N%' AND EXISTS(SELECT 1 FROM addresses a WHERE a.State = st.State)

使用连接执行此操作会慢得多。或者一个更好的例子,如果你想搜索一个项目是否存在于多个表的 1 中。

于 2010-12-16T21:43:54.257 回答