Say I have 3 tables, each with a field foo. How do I get the following records:
- All records where the value of foo exist in all 3 tables?
- All records where the value of foo exist in any 2 tables?
- All records where the value of foo exist in 1 table only?
foo is UNIQUE.
My attempt for #1:
SELECT a.foo
FROM a
WHERE a.foo IN (SELECT b.foo
FROM b
WHERE b.foo IN (SELECT c.foo
FROM c))
For #2, I think I need to do something similar to #1, but for 2 tables at a time {a,b}, {b,c}, {a,c} – and then UNION it? Not sure.
For #3, no clue.
UPDATE: Sample Data
Table1
- foo-a
- foo-b
- foo-c
Table2
- foo-a
- foo-b
Table3
- foo-a
- foo-c
- foo-d
For #1 question, there is 1 record that exist in all 3 tables: foo-a. For #2 question, there are 2 records that exist in 2 tables: foo-b (in Table1 and Table2) and foo-c (in Table1 and Table3). For #3 question, there is 1 record that exist in only 1 table: foo-d.
Since
FOOis unique,For No. 1,
For No. 2,
For No. 3,