I would like to detect whether value is exists or not in each table.I have following table
tableA
code value
a 1
b 2
c 3
tableB
code value
a 4
c 5
d 6
tableC
code value
e 10
f 11
g 12
I want to set variable. and If I set value like value = 'a'
.My desired result is like follows.
value = a
exists in tableA
so that the column named tableA
is set 1
and in tableC
value = a
doesn’t exist so that value 0
was set.
code tableA tableB tableC valueA valueB valueC
a 1 1 0 1 4 null
I tried like follows, but I couldn’t figure out how to join another table.
EXISTS (SELECT 1 FROM tableA WHERE code = 'a')
Are there any smarter ways to achieve this?
If someone has opinion, will you please let me know
Thanks
3
Answers
Assuming the
code
is unique on each table.You can do it using
full outer join
to returns all records when there is a match in left (tableA) or right (tableB) :Or using
USING
instead ofON
onfull outer join
:Result :
Demo here
SelVazis answer is good and clean. however it will not return a result row if the value is not found in any of the tables. And multiple result rows if the value is in one or more tables more then once. Therefore it is better to first make a reponse table and look the answer up in that response table:
In this case i asume you want all values returned from the tables, so I string aggregated them. Feel free to replace that with min, max or whatever floats your boat.
DB fiddle for completeness here
I’d probably just join the three data sets you are looking for. You can do this with pseudo full outer joins (as there is no real join criteria) or with a cross join of aggregations:
(For the full outer joins you could replace
select min(value) as val
byselect code, value as val
andfrom a cross join b cross join c
byfrom a full outer join b using (code) full outer join c using (code)
).Disclaimer: If the value can be null in the tables and you would want to show this as value exists, but value is null, then the above query would have to be adjusted for this.