Grentley Grentley - 5 months ago 16
MySQL Question

Select unique values from the same column in two tables

I'm just playing with SQL and want to achieve the following result
I have the following tables:

TABLE_1 ID NAME
1 CAR
2 ANIMAL
5 ROCK

TABLE_2 ID NAME
1 GRASS
2 ROCKET
3 STONE
4 DOG


I want my query to return unique ID values from both tables:

ID
3
4
5


I have tried using DISTINCT and FULL OUTER JOINS, but without success.
Any help would be appreciated.

Answer

You can use UNION ALL , group it and use the HAVING clause :

SELECT ID FROM (
    SELECT ID FROM Table_1
    UNION ALL
    SELECT ID FROM Table_2)
GROUP BY ID
HAVING COUNT(*) = 1
Comments