0

我有两张桌子TableATableB. TableA有一列newValueoldValueTableB有一列value

我想要以下结果:从TableA其中newValue存在TableBoldValue不存在的地方获取所有行TableB

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

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

(ui:我没有找到这个问题的属性标题)。

编辑:

我尝试的第一件事是:

SELECT newValue, oldValue
FROM TableA
WHERE newValue IN (SELECT value FROM TableB) 
  AND oldValue NOT IN (SELECT value FROM Table B)

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

4

6 回答 6

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
于 2013-09-11T10:45:57.630 回答
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)
于 2013-09-11T10:46:11.163 回答
0

如果你在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)

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)
于 2013-09-11T10:52:26.157 回答
-1

您可以使用单一存在条件来执行此操作。

 SELECT newValue, oldValue
 FROM TableA a
 WHERE exists 
 (
  SELECT 1 FROM TableB b 
  where a.newValue = b.value 
  and a.oldValue != b.value)
于 2013-09-11T11:14:00.267 回答
-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)
于 2013-09-11T10:39:01.977 回答
-1

请试试:

select * from TableA where newValue in (select value from TableB)
union
select * from TableA where oldValue not in (select value from TableB)
于 2013-09-11T10:40:03.040 回答