我需要比较2个表来查找重复项,但这些字段允许重复。
For Example:
Tbl1:
455
7991
7991
Tbl2:
455
7991
7991
7991
我需要编写一个查询,显示表2中有一个额外的7991.我尝试了一个正确的连接,但它仍然找到匹配,因此它无法正常工作。如果有人能指出我正确的方向,我会非常感激。谢谢!
答案 0 :(得分:2)
SELECT t1.colname
FROM ( SELECT colname
, COUNT(colname) AS colCount
FROM tbl1
GROUP BY colname
) t1
INNER JOIN ( SELECT colname
, COUNT(colname) AS colCount
FROM tbl2
GROUP BY colname
) t2 ON t1.colname = t2.colname
AND t1.colCount <> t2.colCount
答案 1 :(得分:1)
如果您的数据库支持FULL OUTER JOIN(不是MySQL),这将为您提供两个表之间的所有差异:
SELECT
T1.x,
COALESCE(T1.cnt, 0) AS T1_count,
COALESCE(T2.cnt, 0) AS T2_count
FROM
(
SELECT x, COUNT(*) AS cnt
FROM Tbl1
GROUP BY x
) T1
FULL OUTER JOIN
(
SELECT x, COUNT(*) AS cnt
FROM Tbl2
GROUP BY x
) T2
ON T1.x = T2.x
WHERE T1.cnt <> T2.cnt