1
SELECT c1, c2, c3
FROM 
(SELECT * FROM table1
UNION ALL
SELECT * FROM table2
UNION ALL
SELECT * FROM table3
UNION ALL
SELECT * FROM table4) data
GROUP BY c1, c2, c2
HAVING (COUNT(*) > 1)

我不能只找到共同的重复行。此查询演示了常见示例数据表 1 和 2 中的所有数据 .. 我只想要所有表中常见的数据有什么帮助吗?

4

4 回答 4

3

这将返回在所有四个表中找到的重复记录

SELECT c1,c2,c3
FROM   (
           SELECT *
           FROM   table1
           UNION ALL
           SELECT *
           FROM   table2
           UNION ALL
           SELECT *
           FROM   table3
           UNION ALL
           SELECT *
           FROM   table4
       ) DATA
GROUP BY c1, c2, c3
HAVING (COUNT(*) >3)
于 2013-02-18T14:28:59.073 回答
2

SQLServer2005+中INTERSECT的另一种选择

SELECT c1, c2, c3
FROM Table1
INTERSECT
SELECT c1, c2, c3
FROM Table2
INTERSECT
SELECT c1, c2, c3
FROM Table3
INTERSECT
SELECT c1, c2, c3
FROM Table4
于 2013-02-18T14:22:33.207 回答
1

假设您想要每个表中共有的所有记录,请在每个表上使用INNER JOIN

SELECT t1.c1, t1.c2, t1.c3
FROM Table1 t1
    INNER JOIN Table2 t2 ON t1.c1 = t2.c1 AND t1.c2 = t2.c2 AND t1.c3 = t2.c3
    INNER JOIN Table3 t3 ON t1.c1 = t3.c1 AND t1.c2 = t3.c2 AND t1.c3 = t3.c3
    INNER JOIN Table4 t4 ON t1.c1 = t4.c1 AND t1.c2 = t4.c2 AND t1.c3 = t4.c3

这将返回每个表中的所有匹配记录。

这是一个示例SQL Fiddle

于 2013-02-18T14:08:14.170 回答
1

我不知道这是否是拼写错误,但在您的GROUP BY条款中,没有c3并且您有 double c2。它应该是

SELECT c1, c2, c3
FROM 
    (
        SELECT * FROM table1
        UNION ALL
        SELECT * FROM table2
        UNION ALL
        SELECT * FROM table3
        UNION ALL
        SELECT * FROM table4
    ) data
GROUP BY c1, c2, c3
HAVING (COUNT(*) > 1)
于 2013-02-18T14:05:15.980 回答