重复多个表sql

时间:2013-02-18 14:03:38

标签: sql

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 个答案:

答案 0 :(得分: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)

答案 1 :(得分: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

答案 2 :(得分:1)

我不知道它是否是拼写错误,但在您的GROUP BY条款中,没有c3,而您有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)

答案 3 :(得分: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