比较两个sql表时输出不匹配的列

时间:2012-08-15 19:15:39

标签: sql

我需要构建一个查询,我只能输出两个表A和B(相同结构)中不匹配的列

例如,表A和B都有10列,具有相同的3个主键。 (这样做的原因是在表A或表B中找到数据输入错误)

例如,表A具有以下值: A B C 1 2 3 4 5 6 7(这是一行,A B C是主键的值) 表B具有值 A B C 1 2 3 4 5 6 8(这是一行,A B C是主键的值)

正如您所看到的,第10列具有不同的值(表A中为7,表B中为8)。 查询的结果应该是第1,2,3和1列。 10,以及表B中的值。

2 个答案:

答案 0 :(得分:0)

返回不同的行实际上非常简单:

select t1.A, t1.B, t1.C
from table1 t1
inner join table2 t2 on t1.A = t2.A and t1.B = t2.B and t1.C = t2.C
where t1.C1 != t2.C1 or t1.C2 != t2.C2 -- and so on for the remaining columns

这将返回不同行的主键。如果你真的需要列出它们不同的列的名称,它将变得更加复杂,因为你需要为每一行返回相同数量的列。您不能拥有动态数量的列。

答案 1 :(得分:0)

您可以创建一个联合查询,例如:

    SELECT Table2.Key1, Table2.Key2, Table2.Key3, CASE WHEN Table1.Value1 <> Table2.Value1 THEN 'Value1' END AS DifferingFields
    FROM Table2 LEFT JOIN Table1 ON Table2.Key1 = Table1.Key1 AND Table2.Key2 = Table1.Key2 AND Table2.Key3 = Table1.Key3
    WHERE Table1.Value1 <> Table2.Value1
    UNION ALL
    SELECT Table2.Key1, Table2.Key2, Table2.Key3, CASE WHEN Table1.Value2 <> Table2.Value2 THEN 'Value2' END
    FROM Table2 LEFT JOIN Table1 ON Table2.Key1 = Table1.Key1 AND Table2.Key2 = Table1.Key2 AND Table2.Key3 = Table1.Key3
    WHERE Table1.Value2 <> Table2.Value2
    UNION ALL
    SELECT Table2.Key1, Table2.Key2, Table2.Key3, CASE WHEN Table1.Value3 <> Table2.Value3 THEN 'Value3' END
    FROM Table2 LEFT JOIN Table1 ON Table2.Key1 = Table1.Key1 AND Table2.Key2 = Table1.Key2 AND Table2.Key3 = Table1.Key3
    WHERE Table1.Value3 <> Table2.Value3
    [... add statements for the remaining value fields ...]

这将返回3个关键字段的值,以及包含不同值的字段的名称。

对于Microsoft Access,请使用:

    SELECT Table2.Key1, Table2.Key2, Table2.Key3, IIF(Table1.Value1 <> Table2.Value1,"Value1","") AS DifferingFields
    FROM Table2 LEFT JOIN Table1 ON Table2.Key1 = Table1.Key1 AND Table2.Key2 = Table1.Key2 AND Table2.Key3 = Table1.Key3
    WHERE Table1.Value1 <> Table2.Value1
    UNION ALL
    SELECT Table2.Key1, Table2.Key2, Table2.Key3, IIF(Table1.Value2 <> Table2.Value2, "Value2","")
    FROM Table2 LEFT JOIN Table1 ON Table2.Key1 = Table1.Key1 AND Table2.Key2 = Table1.Key2 AND Table2.Key3 = Table1.Key3
    WHERE Table1.Value2 <> Table2.Value2
    UNION ALL
    SELECT Table2.Key1, Table2.Key2, Table2.Key3, IIF(Table1.Value3 <> Table2.Value3, "Value3","")
    FROM Table2 LEFT JOIN Table1 ON Table2.Key1 = Table1.Key1 AND Table2.Key2 = Table1.Key2 AND Table2.Key3 = Table1.Key3
    WHERE Table1.Value3 <> Table2.Value3

如果您考虑以下数据:

表1:
Key1 Key2 Key3 Value1 Value2 Value3
1 2 3 4 5 6
1 2 4 4 5 8
1 2 5 4 5 10
1 2 6 4 6 10

表2:
Key1 Key2 Key3 Value1 Value2 Value3
1 2 3 4 5 7
1 2 4 4 5 9
1 2 5 4 5 11
1 2 6 4 5 11

你得到的结果如下:
Key1 Key2 Key3 DifferingFields
1 2 6 Value2
1 2 3 Value3
1 2 4 Value3
1 2 5 Value3
1 2 6 Value3