我有一个非常大的sql语句我必须对其进行修改。在其中一个表中有四个int列,我必须排除2个集合。如果我只想排除一个表的值,那么使用except语句非常简单。我可以这样做:
select *
from Table Z
except(
select *
from Table Z
where (A= 2 and B= 10 and C= 3 and D= 90)
or (A= 2 and B= 17 and C= 100 and D= 90))
但是我无法使用where语句来使用它。我只想要排除这两组组合。在真实语句中,选择中有六个不同的表和各种case语句的连接。
我尝试了一些事情似乎没什么用。
任何想法都将不胜感激!
谢谢!
答案 0 :(得分:4)
为什么复杂EXCEPT
?这不行吗?:
SELECT *
FROM Table Z
WHERE NOT ( ( A= 2 and B= 10 and C= 3 and D= 90)
OR ( A= 2 and B= 17 and C= 100 and D= 90)
)
答案 1 :(得分:1)
只需使用NOT
运算符:
SELECT *
FROM Table Z
WHERE NOT ((A = 2 and B = 10 and C = 3 and D = 90)
OR (A = 2 and B = 17 and C = 100 and D = 90))
或,应用De Morgan's laws,
SELECT *
FROM Table Z
WHERE (NOT (A = 2 and B = 10 and C = 3 and D = 90))
AND (NOT (A = 2 and B = 17 and C = 100 and D = 90))
答案 2 :(得分:0)
尝试NOT IN例如。
SELECT * FROM Table1 WHERE Table1.ID NOT IN (SELECT ID FROM Table1 WHERE Somewhereclause)
在你的情况下:
select *
from Table Z
WHERE Z.ID NOT IN (
select ID
from Table Z
where (A= 2 and B= 10 and C= 3 and D= 90)
or (A= 2 and B= 17 and C= 100 and D= 90))
答案 3 :(得分:0)
以下是两种方式:
SELECT * FROM TABLE Z
WHERE Z.ID NOT IN
(SELECT ID FROM TABLE Z WHERE (A= 2 AND B= 10 AND C= 3 AND D= 90) OR (A= 2 AND B= 17 AND C= 100 AND D= 90))
第二种方式可能表现得更好......不是IN可能有问题:
SELECT * FROM TABLE Z
LEFT JOIN TABLE Z2
ON
Z.Id = Z2.ID
WHERE (Z2.A= 2 AND Z2.B= 10 AND Z2.C= 3 AND Z2.D= 90) OR (Z2.A= 2 AND Z2.B= 17 AND Z2.C= 100 AND Z2.D= 90)) WHERE Z2 IS NOT NULL
密切注意第二个......我不是百分百肯定的。我先尝试第一个,如果遇到性能问题,只使用第二个。
答案 4 :(得分:0)
这将为您提供与示例查询相同的结果,并且只需要一个SELECT语句。
SELECT *
FROM Table_Z
WHERE NOT (A= 2 and B= 10 and C= 3 and D= 90)
AND NOT (A= 2 and B= 17 and C= 100 and D= 90)