[英]SQL query - how to use exist and not exist conditions at the same time
I have two tables TableA
and TableB
. 我有两个表
TableA
和TableB
。 TableA
has a column newValue
and oldValue
. TableA
具有一列newValue
和oldValue
。 TableB
has a column value
. TableB
具有列value
。
I want the following result: get all the rows from TableA
where newValue
exist in TableB
and oldValue
not exist in TableB
. 我想要以下结果:从
TableA
获得所有行,其中newValue
在TableB
存在,而oldValue
在TableB
不存在。
Both tables has many rows so performance is important! 两个表都有很多行,因此性能很重要!
How would you accomplish that in SQL Server 2010/2012? 在SQL Server 2010/2012中如何实现?
(ui: I found no property title for this question). (用户界面:我没有找到此问题的产权)。
Edit: 编辑:
The first thing I tried is: 我尝试的第一件事是:
SELECT newValue, oldValue
FROM TableA
WHERE newValue IN (SELECT value FROM TableB)
AND oldValue NOT IN (SELECT value FROM Table B)
But this is inefficient and has poor performance on my database. 但这效率低下,并且数据库性能不佳。 I'm looking for other solutions.
我正在寻找其他解决方案。
I think avoiding EXISTS
and IN
helps with speed here: 我认为避免
EXISTS
和IN
有助于提高速度:
SELECT
*
FROM TableA
WHERE
(SELECT TOP 1 1 FROM TableB WHERE value = newValue) IS NOT NULL
AND
(SELECT TOP 1 1 FROM TableB WHERE value = oldValue) IS NULL
You can exists use exists/not exists 您可以存在使用存在/不存在
SELECT newValue, oldValue
FROM TableA as t1
where exists(SELECT value FROM TableB as t2 where t1.newValue=t2.value) and
not exists(SELECT value FROM TableB as t3 where t1.olvalue=t3.value)
If you have indexes on value
, newvalue
and oldvalue
, you can try this: 如果您具有
value
, newvalue
和oldvalue
索引,则可以尝试以下操作:
select
a.newValue, a.oldValue
from TableA as a
where
a.newValue in (select distinct b.value from TableB as b) and
a.oldValue not in (select distinct b.value from TableB as b)
or exists
: 或
exists
:
select
a.newValue, a.oldValue
from TableA as a
where
exists (select * from TableB as b where b.value = a.newValue) and
not exists (select * from TableB as b where b.value = a.oldValue)
Select Distinct A.*
From TableA A
Inner Join TableB B on A.newValue = B.Value
Where A.OldValue NOT In (Select Value From TableB)
Please try: 请试试:
select * from TableA where newValue in (select value from TableB)
union
select * from TableA where oldValue not in (select value from TableB)
You can do it with single exist condition. 您可以使用单个存在条件来执行此操作。
SELECT newValue, oldValue
FROM TableA a
WHERE exists
(
SELECT 1 FROM TableB b
where a.newValue = b.value
and a.oldValue != b.value)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.