[英]Alternate of Except in SQL Server
I want to get results from the following table. 我想从下表中获得结果。 Get all ID and treetypes except Apple having Id=102.
获取除Id = 102的Apple之外的所有ID和treetype。
Id TreeType
---------------------
99 Apple
99 Mango
102 Orange
101 Blackberry
102 Apple
Result will be. 结果将是。
Id TreeType
---------------------
99 Apple
99 Mango
102 Orange
101 Blackberry
One way we can get result from following query. 我们可以通过以下查询获得结果的一种方法。
select id, TreeType
from x
except
select id, TreeType
from x
where id = 102 and TreeType = 'Apple'
It it possible to get the result from one select statement? 可以从一个select语句中获得结果吗?
I just want to avoid because of on actual scenario it become very costly for me. 我只是想避免,因为在实际情况下它对我来说变得非常昂贵。
How about just 怎么样
SELECT id,TreeType
FROM x
WHERE NOT(id = 102 AND TreeType = 'Apple')
This did trip me up at first though - I wanted to think WHERE (id <> 102 AND TreeType <> 'Apple')
would work but it doesn't. 虽然这确实让我感到
WHERE (id <> 102 AND TreeType <> 'Apple')
- 我想要认为WHERE (id <> 102 AND TreeType <> 'Apple')
可以工作,但事实并非如此。 This makes sense when you rethink it as a table of bools - in that case it'd be 当你重新考虑它作为一个bools表时,这是有道理的 - 在这种情况下它就是
id opr. TreeType
======================
true AND false -- 99 apple: false
true AND true -- 99 mango: true
true AND false -- 102 orange: false
true AND true -- 101 blackberry: true
false AND true -- 102 apple: false
Using the above syntax, we get just the row we want to target to be true and use NOT
. 使用上面的语法,我们只得到我们想要定位的行为true并使用
NOT
。
id opr. TreeType
======================
false AND false -- 99 apple: not(false) = true
false AND false -- 99 mango: not(false) = true
true AND false -- 102 orange: not(false) = true
false AND true -- 101 blackberry: not(false) = true
true AND true -- 102 apple: not(true) = false
Another solution is using NOT EXISTS
like this- 另一个解决方案是使用
NOT EXISTS
这样的 -
SELECT id,TreeType
FROM x t
WHERE NOT EXISTS
(
SELECT 1 FROM x
WHERE
id = t.id AND TreeType = t.TreeType
AND id = 102
AND TreeType = 'Apple'
)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.