0

我想查找UNION两个 select 语句中不存在但存在于 table 中的记录t1。我就是这样做的。有没有更好的方法来做到这一点?

UPDATE t1
SET    t1.col1 = 0
WHERE  NOT EXISTS (
    SELECT tab2.col2
    FROM   tab2,
           tab3
    WHERE  NOT EXISTS (SELECT *
                       FROM   tab4,
                              tab5
                       WHERE  tab2.col3 = tab4.col3
                              AND tab4.col4 = tab5.col4
                              AND tab5.col5 IN ( 'TT', 'YY' ))
           AND tab3.col2 = tab2.col2
           AND tab2.col2 NOT IN(SELECT DISTINCT col2
                                FROM   tab2_uk WITH (nolock))
           AND t1.col2 = tab3.col2
           AND tab3.date IS NULL
           AND ( Isnull(tab2.pos, 0) > 0
                  OR Isnull(tab2.op, 0) > 0
                  OR Isnull(tab2.co, '-1') <> '-1' )
    UNION
    SELECT tab6.col2
    FROM   dbo.tab6 WITH (nolock),
           dbo.tab3 WITH (nolock)
    WHERE  NOT EXISTS (SELECT *
                       FROM   tab4,
                              tab5
                       WHERE  tab6.col3 = tab4.col3
                              AND tab4.col4 = tab5.col4
                              AND tab5.col5 IN ( 'TT', 'YY' ))
           AND t1.col2 = tab3.col2
           AND tab3.col2 = tab6.col2
           AND tab6.po > 0
           AND tab3.date IS NULL)
4

1 回答 1

3

我想查找两个 select 语句的 UNION 中不存在的记录

由于UNION唯一删除了两个子查询中的完整重复项NOT EXISTS,因此您可以跳过此(可能很昂贵)步骤,只需检查每个单独的子查询。(NOT) EXISTS无论如何,这往往是检查存在的最快方法。

我还将您的 s 重写JOIN为现代 ANSI 语法。否则我保持不变:

UPDATE t1
SET    t1.col1 = 0
WHERE  NOT EXISTS (
     SELECT tab2.col2
     FROM   tab2
     JOIN   tab3 ON tab3.col2 = tab2.col2
     WHERE  NOT EXISTS (
        SELECT *
        FROM   tab4
        JOIN   tab5 ON tab5.col4 = tab4.col4
        WHERE  tab2.col3 = tab4.col3
        AND    tab5.col5 IN ('TT', 'YY')
        )
     AND tab2.col2 NOT IN(SELECT DISTINCT col2
                          FROM   tab2_uk WITH (nolock))
     AND tab3.col2 = t1.col2
     AND tab3.date IS NULL
     AND ( Isnull(tab2.pos, 0) > 0
        OR Isnull(tab2.op, 0) > 0
        OR Isnull(tab2.co, '-1') <> '-1' )
     )
AND  NOT EXISTS (
        SELECT tab6.col2
        FROM   dbo.tab6 WITH (nolock)
        JOIN   dbo.tab3 WITH (nolock) ON tab3.col2 = tab6.col2
        WHERE  NOT EXISTS (
           SELECT *
           FROM   tab4
           JOIN   tab5 ON tab5.col4 = tab4.col4
           WHERE  tab4.col3 = tab3.col3
           AND    tab5.col5 IN ('TT', 'YY')
           )
        AND tab6.po > 0
        AND tab3.col2 = t1.col2
        AND tab3.date IS NULL
        )
于 2013-01-08T23:49:19.930 回答