可以使用SQL语句中的JOIN语句来比较3个表,并使用CASE语句将匹配和未匹配的结果分别放在两张表中。
示例代码:
INSERT INTO matched_table SELECT table1., table2., table3.* FROM table1 INNER JOIN table2 ON table1.common_attribute = table2.common_attribute INNER JOIN table3 ON table1.common_attribute = table3.common_attribute
INSERT INTO unmatched_table SELECT * FROM ( SELECT table1.*, 'table1' AS tablename FROM table1 LEFT JOIN table2 ON table1.common_attribute = table2.common_attribute LEFT JOIN table3 ON table1.common_attribute = table3.common_attribute WHERE table2.common_attribute IS NULL AND table3.common_attribute IS NULL
UNION ALL
SELECT table2.*, 'table2' AS tablename FROM table2 LEFT JOIN table1 ON table1.common_attribute = table2.common_attribute LEFT JOIN table3 ON table2.common_attribute = table3.common_attribute WHERE table1.common_attribute IS NULL AND table3.common_attribute IS NULL
UNION ALL
SELECT table3.*, 'table3' AS tablename FROM table3 LEFT JOIN table1 ON table1.common_attribute = table3.common_attribute LEFT JOIN table2 ON table2.common_attribute = table3.common_attribute WHERE table1.common_attribute IS NULL AND table2.common_attribute IS NULL ) AS unmatched_records;
下一篇:比较3个随机数出现错误