0

我正在将 SQL Server 中的原始表与更新表进行比较。我试图找出有多少“第一个数字”发生了变化。因为他们确实在这个系统中发生了变化。但是,这个查询似乎带回了等于两个表的“第一个数字”。我究竟做错了什么?

select *
from   
    tblBlue
where  
    Exists (Select 'x'
            From tblRed
            Where tblRed.FirstNumber != tblBlue.FirstNumber 
              and tblRed.ID = tblBlue.ID)

示例数据:

tblRed
ID  FirstNumber
1   10 
2   20
3   30
4   40

tblBlue
1   5
2   20
3   35
4   40

我希望看到:

1   5
3   35
4

2 回答 2

1

您的查询应该可以工作(参见SQL Fiddle 中的示例。)您能否发布返回错误结果的示例数据?

更清晰的写法:

select  *
from    tblBlue new
join    tblRed old
on      new.ID = red.ID
where   new.FirstNumber <> old.FirstNumber
于 2013-03-29T14:52:47.093 回答
1

更简单的解决方案:使用左连接

SELECT r.*
FROM tblRed r
LEFT JOIN tblBlue b ON b.ID = r.ID AND b.FirstNumber = r.FirstNumber
WHERE b.ID IS NULL

This will return records in tblRed that satisfy one of two conditions: 1) the ID isn't even found in tblBlue, i.e. a new record. or 2) the IDs were found, but the numbers have changed. Because if both the ID is the same and the FirsTNumber is the same, then b.ID will not be NULL, thus a match, and you can exclude it from the resultset of different values.

于 2013-03-29T14:53:46.157 回答