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.
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
Try this:
SELECT ID
FROM (
SELECT ID
FROM TABLE_1
UNION ALL
SELECT ID
FROM TABLE_2) AS t
GROUP BY ID
HAVING COUNT(*) = 1
Try this;)
SELECT ID
FROM(
SELECT DISTINCT ID FROM TABLE1
UNION ALL
SELECT DISTINCT ID FROM TABLE2
) T
GROUP BY ID
HAVING COUNT(ID) = 1
SELECT id FROM table_1 WHERE id NOT IN (SELECT id FROM table_2)
UNION
SELECT id FROM table_2 WHERE id NOT IN (SELECT id FROM table_1)
Construct the intersection manually using UNION. It's easy if you have some unique field in both tables, eg ID:
SELECT id FROM Table 1
WHERE id NOT IN (SELECT id FROM Table 2)
UNION
SELECT id FROM Table 2
WHERE id NOT IN (SELECT id FROM Table 1)
SELECT table_1.id
FROM table_1
WHERE table_1.id NOT IN (SELECT table_2.id FROM table_2)
UNION
SELECT table_2.id
FROM table_2
WHERE table_2.id NOT IN (SELECT table_1.id FROM table_1)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.