I have two tables
tableA (id,randomNumber) (2,1),(3,5),(3,2),(6,0),(8,0),...
tableB (id,randomNumber2) (0,2),(1,3),(2,0),(4,2)...
Now I'd like to fetch id, randomnumber and randomnumber2 where ID IN (0,1,2,3) from both tables.
So that should return:
(2,1), (3,5), (3,2), (0,2), (1,3), (2,0)
I tried constructions with JOIN and LEFT JOIN.
The problem is when the ON clause (JOIN tableB b on a.id=b.id) is not true, it returns NULL for the id. But I also need to know the NULL value. For example for tableB it will return (NULL,2) for the first result.
(2,1), (3,5), (3,2), (NULL,2), (NULL,3), (2,0)
How can I also get the NULL value, should I be using something else ?
JOIN
s are used when the tables have related data. Here, the 2 tables have nothing to do with each other. A better choice would be to use a UNION
.
SELECT id, randomNumber
FROM tableA
WHERE ID IN (0,1,2,3)
UNION ALL
SELECT id, randomNumber2
FROM tableB
WHERE ID IN (0,1,2,3)
Or, just use 2 separate queries and combine the results.
You can use a UNION
with a subquery:
SELECT id, rn
FROM (
SELECT Id, randomNumber rn
FROM tableA
UNION
SELECT Id, randomNumber2
FROM tableB
) t
WHERE id IN (0,1,2,3)
You may want to use a UNION ALL
if you want duplicate values.
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.