通过xyz加入两个表和组

时间:2012-11-06 07:49:12

标签: mysql sql

我有两张桌子

表1:

    ref       status

    abc     1
    abc     1
    abc     2
    abc     3
    abc     5(not in Table2)
    abc     5(not in Table2)

表2:

    ref          status

    abc     1
    abc     1
    abc     2
    abc     3
    abc             4(not in Table1)
    abc     4(not in Table1)

我想加入这两个表并执行分组,以便最终结果如下所示:

结果表:         参考状态

    abc     1
    abc     2
    abc     3
    abc     4
    abc     5

我试过这个

    SELECT DISTINCT Table1.ref, Table1.status, Table2.ref, Table2.status
    FROM Table1, Table2
    GROUP BY Table1.ref, Table1.status, Table2.ref, Table2.status;

2 个答案:

答案 0 :(得分:6)

SELECT DISTINCT ref, status
FROM
(
    SELECT ref, status
    FROM Table1
    UNION ALL
    SELECT ref, status
    FROM Table2
) x

SQL Fiddle example

答案 1 :(得分:0)

请尝试以下代码:

SELECT DISTINCT ref, status
FROM Table1
UNION 
SELECT DISTINCT ref, status
FROM Table2