确保不同表中的2列逐行MySQL相同

时间:2019-02-21 15:37:19

标签: mysql sql

我希望逐行比较两个不同的表,以确保文件名和与文件名关联的计数都匹配。如果任何一个都不匹配,我想输出两个不匹配的行。

我正在使用MySQL作为该操作的数据库

例如

Expected                      Actual
FileName    Count             FileName    Count
name1.txt    4                name1.txt    4
name2.txt    7                name2.txt    7
name3.txt    4                name4.txt    4  (invalid filename)
name5.txt    4                name5.txt    5  (invalid count)

Output:
The fOllowing rows did not match:
Expected:                     Actual:
name3.txt    4                name4.txt    4 (because of filename)
name5.txt    4                name5.txt    5 (because counts are diff)

此操作的目的是用于验证脚本。有两个表,一个用于预期结果,一个用于实际结果。 sql将比较每个表中的行,以确保它们相同。每个表中有4列。为了使这些表“相同”,必须在两个表中都找到文件名和与该文件名关联的计数。如果那没有发生,我想输出无法找到匹配项的行。

1 个答案:

答案 0 :(得分:0)

您想要NOT EXISTS

表1:

SELECT t1.* 
FROM table1 t1
WHERE NOT EXISTS (SELECT 1 FROM table2 t2 WHERE t2.filename = t1.filename AND t1.count = t2.count);

表2:

SELECT t2.* 
FROM table2 t2
WHERE NOT EXISTS (SELECT 1 FROM table1 t1 WHERE t2.filename = t1.filename AND t1.count = t2.count);

如果您想将它们整理为一个结果集,则使用union all

SELECT t1.filename, t1.count, 'table1' as table_name
FROM table1 t1
WHERE NOT EXISTS (SELECT 1 FROM table2 t2 WHERE t2.filename = t1.filename AND t1.count = t2.count)
UNION ALL
SELECT t2.filename, t2.count, 'table2'
FROM table2 t2
WHERE NOT EXISTS (SELECT 1 FROM table1 t1 WHERE t2.filename = t1.filename AND t1.count = t2.count);