I have a 2 tables with a many-2-many relationship:
tableA (ida, valA)
tableB (idb, valB)
tableAB (ida, idb)
I need one query that should return in every tupple:
(ida, idb, 0/1 if related or not)
Here is some input / output example:
tableA
ida valA
1 b
2 s
3 l
tableB
idb valB
11 aaa
22 bbb
33 ccc
tableAB
ida idb
1 11
2 33
Expected results:
ida idb is_exists
1 11 1
2 11 0
1 33 0
2 33 1
Note that I don’t need permutations which are always 0, for example ida=3 or idb=22
this is because it means that in a matrix the whole row or column is 0 (this shows that the row has no relation whatsoever with the other table)
\ ida | | |
idb \ | 1 | 2 | 3
---------------------------
11 | 1 | 0 | 0
---------------------------
22 | 0 | 0 | 0
---------------------------
33 | 0 | 1 | 0
What you need is a driving table that has all possible pairs. One way to get this is from TableA and TableB, using a cross join:
After that, the query just summarizes and determines whether there is a matching record in TableAB.