How to verify if two tables have exactly the same data?

前端 未结 8 680
梦毁少年i
梦毁少年i 2020-12-08 10:34

Basically, we have one table (original table) and it is backed up into another table (backup table); thus the two tables have exactly the same sche

相关标签:
8条回答
  • 2020-12-08 11:29

    Try the following to compare two tables:

    SELECT 'different' FROM DUAL WHERE EXISTS(
        SELECT * FROM (
            SELECT /*DISTINCT*/ +1 AS chk,a.c1,a.c2,a.c3 FROM a
            UNION ALL
            SELECT /*DISTINCT*/ +1 AS chk,b.c1,b.c2,b.c3 FROM b
        ) c
        GROUP BY c1,c2,c3
        HAVING SUM(chk)<>2
    )
    UNION SELECT 'equal' FROM DUAL
    LIMIT 1;
    
    0 讨论(0)
  • 2020-12-08 11:31

    I would write three queries.

    1. An inner join to pick up the rows where the primary key exists in both tables, but there is a difference in the value of one or more of the other columns. This would pick up changed rows in original.

    2. A left outer join to pick up the rows that are in the original tables, but not in the backup table (i.e. a row in original has a primary key that does not exist in backup). This would return rows inserted into the original.

    3. A right outer join to pick up the rows in backup which no longer exist in the original. This would return rows that have been deleted from the original.

    You could union the three queries together to return a single result set. If you did this you would need to add a column to indicate what type of row it is (updated, inserted or deleted).

    With a bit of effort, you might be able to do this in one query using a full outer join. Be careful with outer joins, as they behave differently in different SQL engines. Predicates put in the where clause, instead of the join clause can sometimes turn your outer join into an inner join.

    0 讨论(0)
提交回复
热议问题