我有2个数据库,DB1中只有1个表,DB2中有2个表。 DB1.table1中的每条记录都被拆分并分别存储在DB1.table1和DB @ .table2中。
For example, DB1 has a table1 which looks like
Student_Name Id Address Attendance Marks
------------ -- ------- ---------- -----
John 1 90th st 70 90
The records that are transferred from DB1.table1 are stored in DB2.table and DB2.table2 in the following manner
DB2.table 1: Id Student_Name Address
-- ------------ -------
1 John 90th st
DB2.table 2: Id Attendance Marks
-- ---------- -----
1 70 90
我想编写一个测试用例,以确保将DB1中的所有数据都复制到DB2。我写了一些查询来确定DB1中的记录是否未复制到DB2。除了找出丢失的记录之外,我还想逐列检查每条记录,以确保DB1和DB2中的值相同。
从上面的例子中,我想检查ID = 1,如果DB2.table1 Student_name = DB1.table1 Student_name,DB2.table1 Address = DB1.table1 Address,依此类推..
如果我有1000列怎么办?我应该写一个长脚本来检查每一列吗?不,这是进行此类测试的最佳方式吗?有没有可以使用的工具或者我应该写下脚本?
答案 0 :(得分:0)
这会在Id
和db1.table1
中找到db2.table1
中没有匹配项的db2.table2
行。
它假定两个表中的列名称相同,并且db2.table1
或db2.table2
中存在的任何列都应在db1.table1
中具有匹配的列名称。因此,如果db2.table2
有一个名为Foo
的列,db1.table1
也必须有一个名为Foo
的列。如果db2.table1
包含名为Bar
的列,则db1.table1
也必须包含名为Bar
的列。如果该列存在于db2
但不存在于db1
中,则会出现MySQL错误。
希望这就是你要找的东西!
header("Content-type: text/plain");
// connect with mysqli
// get a list of columns in db2.table1 and db2.table2
$columns = array();
$query = mysqli_query("SELECT table_name, column_name FROM information_schema.columns WHERE table_schema = 'db2' AND table_name IN ('table1', 'table2')");
while ($row = $mysqli_fetch_assoc($query)) {
$columns[$row["table_name"]][] = "db1.table1.{$row["column_name"]} = db2.{$row["table_name"]}.{$row["column_name"]}";
}
$query = mysqli_query("
SELECT db1.table1.Id
FROM
db1.table1
LEFT JOIN db2.table1
ON ". implode(" AND ", $columns["table1"]) ."
LEFT JOIN db2.table2
ON ". implode(" AND ", $columns["table2"]) ."
WHERE
db2.table1.Id IS NULL
OR db2.table2.Id IS NULL
");
while (list($id) = mysqli_fetch_row($query)) {
echo "ID {$id} does not match\n";
}
答案 1 :(得分:0)
您可以使用union all和group by:
执行此操作select Student_Name, Id, Address, Attendance, Marks,
(case when max(which) = 'db1' then 'Missing in db2'
when min(which) = 'db2' then 'Missing in db1'
end) as why
from ((select 'db1' as which, Student_Name, Id, Address, Attendance, Marks
from db1.table1 t
) union all
(select 'db2' as which, t1.Student_Name, t1.id, t1.Address, t2.Attendance, t2.Marks
from db2.table1 t1 join
db2.table2 t2
on t1.id = t2.id
)
) u
group by Student_Name, Id, Address, Attendance, Marks
having count(distinct which) = 1
答案 2 :(得分:0)
此查询的结果将为您提供DB2中与DB1不同的行数,如果行不存在但它也应该计数。如果结果为0,一切正常。
SELECT
COUNT(*) AS difference
FROM
DB1.table1 AS d1t1
LEFT JOIN DB2.table1 AS d2t1
USING (Id)
LEFT JOIN DB2.table2 AS d2t2
USING (Id)
WHERE
(d1t1.Student_Name <> d2t1.Student_Name)
OR (d1t1.Address <> d2t1.Address)
OR (d1t1.Attendace <> d2t2.Attendace)
OR (d1t1.Marks <> d2t2.Marks)