2011-10-11 84 views
5
Table 1    Table 2 
Number | Code  Code | Description 
1234  A   A  Something 
1235  B   C  Something else 
1246  C   D  Something other 
1247  A 
1248  B 
1249  A 

我想找到不同Code值,並得到這樣的回報:SQL查詢在兩個表中查找不同的值?

1 | 2 
------- 
A  A 
B 
C  C 
     D 

我無法弄清楚如何編寫的SQL查詢將返回我上述結果。任何人有任何這樣或類似的查詢經驗?

回答

10

在適當的RDBMS:

SELECT 
    T1.Code, T2.Code 
FROM 
    (SELECT DISTINCT Code FROM Table1) T1 
    FULL OUTER JOIN 
    (SELECT DISTINCT Code FROM Table2) T2 
       ON T1.Code = T2.Code 

在MySQL的使用UNION刪除重複

SELECT 
    T1.Code, T2.Code 
FROM 
    Table1 T1 
    LEFT OUTER JOIN 
    Table2 T2 ON T1.Code = T2.Code 
UNION 
SELECT 
    T1.Code, T2.Code 
FROM 
    Table1 T1 
    RIGHT OUTER JOIN 
    Table2 T2 ON T1.Code = T2.Code 
+0

「正確的RDBMS「不會生成空值,可能會使用關係值屬性進行這種查詢;) – onedaywhen

2

什麼你要找的是一個full outer join

select a.code as code_1,b.code as code_2 
from(
    select code 
    from table1 
    group by 1 
)a 
full outer join(
    select code 
    from table2 
    group by 1 
)b 
using(code) 
order by 1; 
+0

JOIN什麼樣的OUTER的? – gbn

+0

@gbn - 'full outer join':http://en.wikipedia.org/wiki/Join_(SQL)#Full_outer_join – 2011-10-11 19:35:35

+0

是的,但你必須添加它:-)你會看到我在下面使用了一個。 .. – gbn

-1

喜歡的東西:

SELECT DISTINCT tbl1.Code爲1,tbl2.Code FROM TBL 1 LEFT JOIN tbl2的ON tbl1.Code = TBL2 。代碼

+0

這不會讓你成爲最後一行:,D –

+0

哦,是的,我錯過了 - 對不起 – ollie

-1

這實際上看起來像是兩個外連接的聯合。試試這個:

SELECT t1.Code, t2.Code 
FROM Table1 AS t1 
LEFT JOIN Table2 AS t2 ON t1.Code 

UNION 

SELECT t1.Code, t2.Code 
FROM Table1 AS t1 
RIGHT JOIN Table2 AS t2 ON t1.Code 

ORDER BY 1, 2 

的UNION操作將只保留不同的值。

0

訣竅將兩個表中得到不同的值,這樣的事情:

SELECT a.Code, b.code 
FROM 
(--Get the DISTICT Codes from all sets 
    SELECT Distinct Code from Table1 
    UNION SELECT Distinct Code from Table2 
) x Left JOIN 
Table1 a ON x.code = a.Code LEFT JOIN 
Table2 b ON x.code = b.Code 
2

在標準SQL中,使用關係運算符並避免空值:

SELECT Code AS col_1, Code AS col_2 
    FROM Table_1 
INTERSECT 
SELECT Code AS col_1, Code AS col_2 
    FROM Table_2 

UNION 

SELECT Code AS col_1, 'missing' AS col_2 
    FROM Table_1 
EXCEPT 
SELECT Code AS col_1, 'missing' AS col_2 
    FROM Table_2 

UNION 

SELECT 'missing' AS col_1, Code AS col_2 
    FROM Table_2 
EXCEPT 
SELECT 'missing' AS col_1, Code AS col_2 
    FROM Table_1; 
在標準SQL

再次,這次使用的構建MySQL實際支持:

SELECT Code AS col_1, Code AS col_2 
    FROM Table_1 
WHERE EXISTS (
       SELECT * 
       FROM Table_2 
       WHERE Table_2.Code = Table_1.Code 
      ) 

UNION 

SELECT Code AS col_1, 'missing' AS col_2 
    FROM Table_1 
WHERE NOT EXISTS (
        SELECT * 
        FROM Table_2 
        WHERE Table_2.Code = Table_1.Code 
       ) 
UNION 

SELECT 'missing' AS col_1, Code AS col_2 
    FROM Table_2 
WHERE NOT EXISTS (
        SELECT * 
        FROM Table_1 
        WHERE Table_1.Code = Table_2.Code 
       );