比较两个相似表,不同数据库

时间:2017-12-21 02:31:29

标签: sql database compare multiple-databases

我们遇到过这样的问题,即某人对我们想要更改的数据库进行了一些更改。我们有2个数据库副本:几天前的备份及其生产数据库。

我正在尝试比较并获取db1中Statecode的记录!= db2中的Statecode。我该怎么做呢?

我尝试了以下方法,但我认为这是错误的:

SELECT fileId, statecode from DB1..fileBase t1
WHERE EXISTS    
(
    SELECT fileId, statecode from DB2..fileBase t2
    WHERE   t1.statecode = 0 AND
            t1.statecode != t2.statecode AND
            t1.ModifiedBy = '326AC533-DD41-E411-213C-03156D015A13'
)

编辑样本:

    Prod ID                                 Backup ID                      ProdStateCode BackupStateCode
    D4DEEA73-D5B6-E611-80E6-9216FEE69DCF    D4DEEA73-D5B6-E611-80E6-9216FEE69DCF    0          1
    621BD1FA-D1B6-E611-80E6-9216FEE69DCF    621BD1FA-D1B6-E611-80E6-9216FEE69DCF    0          0
    2E4E65F0-D1B6-E611-80E6-9216FEE69DCF    2E4E65F0-D1B6-E611-80E6-9216FEE69DCF    0          0
    35B8FCD9-D0B6-E611-80E6-9216FEE69DCF    35B8FCD9-D0B6-E611-80E6-9216FEE69DCF    0          1

我希望那些Prod StateCode不等于备份状态代码。我也试过

SELECT
  prod.fileId,
  prod.statecode
FROM DB1..fileBase AS prod
INNER JOIN DB2..fileBase AS back
  ON prod.fileId = back.fileId
WHERE prod.statecode != back.statecode

但输出似乎不正确。

1 个答案:

答案 0 :(得分:2)

尝试使用:使用LEFT JOINNOT EXISTS,如下所示,它会为您提供field & statecode的{​​{1}}所在的列表field

中不存在的statecode
db2

SELECT prod.fileId, prod.statecode 
FROM DB1.fileBase AS prod
LEFT JOIN DB2.fileBase AS back ON prod.fileId = back.fileId
    AND prod.statecode = back.statecode
WHERE back.statecode IS NULL