Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL query to find distinct values in two tables?

Tags:

sql

distinct

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

I would like to find the distinct Code values and get a return like this:

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

I can't figure out how to write a SQL query that would return me the above results. Anyone have any experience with a query like this or similar?

like image 570
tomthorgal Avatar asked Oct 11 '11 19:10

tomthorgal


2 Answers

In Standard SQL, using relational operators and avoiding nulls:

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;

Again in Standard SQL, this time using constructs that MySQL actually supports:

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
                  );
like image 187
onedaywhen Avatar answered Nov 03 '22 02:11

onedaywhen


In proper 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

In MySQL... the UNION removes duplicates

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
like image 30
gbn Avatar answered Nov 03 '22 02:11

gbn