我想查找两个select语句的UNION
中不存在但在表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)
答案 0 :(得分:3)
我想找到两个选择的UNION中不存在的记录 语句
由于UNION
仅删除了两个子查询中的完整重复项,因此您可以跳过此(可能很昂贵的)步骤,并在每个子查询上查看NOT EXISTS
。无论如何,(NOT) EXISTS
往往是检查存在的最快方法。
我还将您的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
)