В SQLite есть ли способ проверить, идентичны ли две таблицы? - PullRequest
0 голосов
/ 26 мая 2018

Предположим, что две таблицы находятся в одном файле.Таким образом, вопрос заключается в том, что кроме их имен таблицы идентичны, т. Е. Одна и та же схема, одно и то же содержимое.

Ответы [ 2 ]

0 голосов
/ 26 мая 2018

Я полагаю, что может быть достаточно следующего: -

/*
   Compare Schema and data in tables.

     t1 is the SQL for the first table (mytable) with the table name changed to a common name (table)
     t2 is the SQL for the second table (mytable_copy1) with the table changed to a common name (table)
     (so if t1 and t2 are equal then the schema is the same)

     tablecompare is the logical result of comparing the data of each table with the other table
     except matching rows so if no rows exists then NOT EXISTS will be true (1) AND the two
     and the result will be 1 if both tables exactly match each other.

*/

SELECT 
    (t1 = t1) AND tablecompare  AS test FROM 
            (SELECT 
                replace(sql,'mytable','table') AS t1, -- change the table name to a common name
                replace(sql,'mytable_copy1','table') AS t2, -- change the table name to a common name

                (
                    SELECT NOT EXISTS (SELECT * FROM mytable EXCEPT SELECT * FROM mytable_copy1) 
            AND NOT EXISTS (SELECT * FROM mytable_copy1 EXCEPT SELECT * FROM mytable) 
                ) AS tablecompare
                FROM sqlite_master WHERE name = 'mytable'
) 
  • Обратите внимание, что таблицы mytable и mytable_copy1, поэтому они будут изменены, чтобы отразить две таблицы.

Возможно, менее запутанным (возможно, более) это более затянутое решение: -

/*

   Table Compare

     t1 is the SQL for the first table (mytable) with the table name replace by table
     t2 is the SQL for the second table (mytable_copy1) again table name change to table
     So if t1 = t2 then the schema is identical

     t1count is the number of rows in the first table 
     t2count is the number of rows in the second table
     So if the counts are the same then the tables may be identical

     unioncount is the count of the union of the two tables (not union all) so duiplicates are dropped
     therefore if unioncount is the same as either of the table counts then tables are identical
     NOTE!!! this assumes tables are not WITHOUT ROWID tables (would have to omit the inclusion of rowid NOT TESTED)
     the inclusion of rowid could be dropped (NOT TESTED) if there is an alias of rowid.
*/
SELECT 
    t1 = t1 AND t1count = t2count AND t1count = unioncount AS test FROM 
            (SELECT 
                replace(sql,'mytable','table') AS t1, -- change the table name to a common name
                replace(sql,'mytable_copy1','table') AS t2, -- change the table name to a common name

                (SELECT count() FROM mytable) AS t1count, -- get the number of rows
                (SELECT count() FROM mytable_copy1) AS t2count, -- get the number of rows
                (SELECT count() AS unioncount FROM
            (SELECT rowid,* FROM mytable UNION SELECT rowid,* FROM mytable_copy1)) AS unioncount
                FROM sqlite_master WHERE name = 'mytable'
) ;

Оба решения возвращают один результат строки / столбца 1, если таблицы соответствуют 0, если нет.

Однако, но может потребоваться меньше времени / ресурсов для выполнения отдельных тестов.Например, если схемы не совпадают, ничего не делайте, иначе проверьте количество строк, а если они не совпадают, не делайте окончательную проверку фактической проверки данных.

Проверка Следующие таблицы использовались для проверки:-

Для mytable и mytable_copy1: -

enter image description here

Вышеуказанные оба получены 1 согласно: -

enter image description here

и: -

enter image description here

Когда следующая таблица (mytable_copy2 с измененными данными выделена):-

enter image description here

Результаты были: -

enter image description here

и:-

enter image description here

0 голосов
/ 26 мая 2018

Чтобы сравнить схемы таблиц, посмотрите на операторы в таблице sqlite_master :

SELECT sql FROM sqlite_master WHERE tbl_name IN ('This', 'That');

При сравнении вы должны игнорировать само имя таблицы;Автоматическая замена сложнее, если у вас есть имена столбцов или комментарии, которые содержат имя таблицы.

Чтобы сравнить содержимое, просто используйте составные запросы , чтобы проверить, есть ли какие-либо строки, которые не находятся вдругая таблица:

SELECT NOT EXISTS (SELECT * FROM This
                   EXCEPT
                   SELECT * FROM That)
   AND NOT EXISTS (SELECT * FROM That
                   EXCEPT
                   SELECT * FROM This);
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...