Details:
V
andC
are tablesI want
C
to joinV
on 2 conditions(two C are namedC0
andC1
). Since I must filterV
by columns ofC
andC
‘s child tables separately in the same query, I think joining is needed.V
has many, at least oneC
, and eitherCx
sometimes doesn’t exist.
Because of 3., using inner join to C0
and C1
sometimes cause empty result, but I don’t want get V
‘s white area.
Schema:
V (id) C (id, v_id, name, type)
Query(1):
SELECT V.* FROM V INNER JOIN C AS C0 ON V.id = C0.v_id WHERE C0.type = 0 INNER JOIN C AS C1 ON V.id = C1.v_id WHERE C1.type = 1 WHERE C0.name = 'word' or C1.name = 'word' WHERE C0.name like '%wo%'
Query (2):
SELECT V.* FROM V INNER JOIN C AS C0 ON V.id = C0.v_id WHERE C0.type = 0 INNER JOIN C AS C1 ON V.id = C1.v_id WHERE C1.type = 1 WHERE C0.name = 'word' or C1.name = 'word' WHERE C1.name like '%wo%'
WHERE C0.name = 'word' or C1.name = 'word'
: This clause exists every time.
WHERE Cx.name like '%wo%'
: This clause depends on the time.
Advertisement
Answer
Well… You seem to be looking for an EXISTS
condition with correlated subquery:
SELECT * FROM v WHERE EXISTS (SELECT 1 FROM c WHERE c.c0 = v.c0 OR c.c1 = v.c1)
This will return all records in table v
for which at least one record exists in table c
that satisfies either condition c.c0 = v.c0
or condition c.c1 = v.c1
.
In this situation, the advantage of the correlated subquery against the JOIN
approach is that it avoids multiplying records when more than one match exists in table c
.
If you want to exclude records that meet either condition instead of including them, then just change WHERE EXISTS
to WHERE NOT EXISTS
.