web-dev-qa-db-ja.com

2つのテーブルで異なる値を見つけるためのSQLクエリ?

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値を見つけて、次のような結果を取得したいと思います。

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

上記の結果を返すSQLクエリの書き方がわかりません。このようなクエリの経験がある人はいますか?

7
tomthorgal

適切な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
15
gbn

標準SQLでは、関係演算子を使用し、nullを回避します。

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
                  );
2
onedaywhen

あなたが探しているのは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;
2
user554546

秘訣は、次のように、両方のテーブルから個別の値を取得することです。

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
0
ctupper

これは実際には、2つの外部結合のUNIONのように見えます。これを試して:

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
Paul Sasik