两个显示结果包含来自不同数据库的两个表之间的差异

时间:2015-01-23 08:03:47

标签: sql-server

我有来自两个数据库的两个表,一个是本地另一个是服务器中的一个,所以需要找到两个表中两个表列的所有差异,如图所示。

我需要结果,如下图所示,他们还有其他方法可以找到吗?

当我正在为下面这个查询时,它正在加载但无法生成结果,当我减少条件时它产生结果但我需要适当的整个查询结果。

select DISTINCT 
    tu.ModuleID, 
    tu.AllowAdd, 
    tu.AllowEdit, 
    tu.AllowDelete, 
    tu.AllowSupervision,
    tt.ModuleID,
    tt.AllowAdd,
    tt.AllowEdit,
    tt.AllowDelete,
    tt.AllowSupervision
from 
    t_UserModule tu,
    [smf5.0_check].dbo.t_usermodule tt
where 
    tu.ModuleID = tt.ModuleID
    and tu.OperatorID = tt.OperatorID
    and tu.AllowAdd <> tt.AllowAdd
    or tu.AllowEdit <> tt.AllowEdit
    or tu.AllowDelete <> tt.AllowDelete
    or tu.AllowSupervision <> tt.AllowSupervision

enter image description here

3 个答案:

答案 0 :(得分:1)

问题出在WHERE子句中。您需要对ORs进行分组。

WHERE
    tu.ModuleID = tt.ModuleID
    and tu.OperatorID = tt.OperatorID
    and (
        tu.AllowAdd <> tt.AllowAdd
        or tu.AllowEdit <> tt.AllowEdit
        or tu.AllowDelete <> tt.AllowDelete
        or tu.AllowSupervision <> tt.AllowSupervision
    )

或者,您可以像这样编写查询:

SELECT 
    tu.ModuleID, 
    tu.AllowAdd, 
    tu.AllowEdit, 
    tu.AllowDelete, 
    tu.AllowSupervision,
    tt.ModuleID,
    tt.AllowAdd,
    tt.AllowEdit,
    tt.AllowDelete,
    tt.AllowSupervision
FROM t_UserModule tu
INNER JOIN [smf5.0_check].dbo.t_usermodule tt
    ON tu.ModuleID = tt.ModuleID
    AND tu.OperatorID = tt.OperatorID
WHERE    
    tu.AllowAdd <> tt.AllowAdd
    OR tu.AllowEdit <> tt.AllowEdit
    OR tu.AllowDelete <> tt.AllowDelete
    OR tu.AllowSupervision <> tt.AllowSupervision

答案 1 :(得分:1)

编辑:我知道我的旧答案存在一些性能问题。这是一个可以处理空值的新答案:

SELECT
    t1.ModuleID, 
    t1.AllowAdd, 
    t1.AllowEdit, 
    t1.AllowDelete, 
    t1.AllowSupervision,
    t2.ModuleID,
    t2.AllowAdd,
    t2.AllowEdit,
    t2.AllowDelete,
    t2.AllowSupervision
FROM
    t_UserModule t1
JOIN 
    [smf5.0_check].dbo.t_usermodule t2
ON
    t1.ModuleID = t1.ModuleID and
    t2.OperatorID = t2.OperatorID
WHERE not exists
  (SELECT
     t1.AllowAdd, 
     t1.AllowEdit,
     t1.AllowDelete,
     t1.AllowSupervision
   INTERSECT
   SELECT
     t2.AllowAdd, 
     t2.AllowEdit,
     t2.AllowDelete,
     t2.AllowSupervision)

答案 2 :(得分:0)

SELECT *
FROM    t_UserModule tu 
FULL JOIN [smf5.0_check].dbo.t_usermodule tt
ON   tu.ModuleID = tt.ModuleID
        AND tu.OperatorID = tt.OperatorID
        AND tu.AllowAdd = tt.AllowAdd
        AND tu.AllowEdit = tt.AllowEdit
        AND tu.AllowDelete = tt.AllowDelete
        AND tu.AllowSupervision = tt.AllowSupervision
WHERE     tu.ModuleID IS NULL OR  tt.ModuleID     IS NULL

如果有可用的列,则需要在连接条件

中执行COALESCE(tu.AllowAdd,-1) = COALESCE(tt.AllowAdd,-1)之类的操作