SQL查询 - 如何同时使用存在且不存在的条件

时间:2013-09-11 10:34:38

标签: sql sql-server

我有两张表TableATableBTableA有一列newValueoldValueTableB有一列value

我想要以下结果:获取TableA newValue中存在TableB oldValue TableB SELECT newValue, oldValue FROM TableA WHERE newValue IN (SELECT value FROM TableB) AND oldValue NOT IN (SELECT value FROM Table B) {{1}}不存在的所有行。

两个表都有很多行,所以性能很重要!

您将如何在SQL Server 2010/2012中实现这一目标?

(u.i。:我没有找到这个问题的财产名称。)

修改

我尝试的第一件事是:

{{1}}

但这样效率很低,而且我的数据库性能很差。我正在寻找其他解决方案。

6 个答案:

答案 0 :(得分:0)

我认为避免EXISTSIN有助于提高速度:

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

答案 1 :(得分:0)

您可以存在使用存在/不存在

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)

答案 2 :(得分:0)

如果您在valuenewvalueoldvalue上有索引,可以试试这个:

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)

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)

答案 3 :(得分:-1)

Select Distinct A.*
From TableA A
     Inner Join TableB B on A.newValue = B.Value
Where A.OldValue NOT In (Select Value From TableB)

答案 4 :(得分:-1)

请尝试:

select * from TableA where newValue in (select value from TableB)
union
select * from TableA where oldValue not in (select value from TableB)

答案 5 :(得分:-1)

你可以用单一的条件来做。

 SELECT newValue, oldValue
 FROM TableA a
 WHERE exists 
 (
  SELECT 1 FROM TableB b 
  where a.newValue = b.value 
  and a.oldValue != b.value)