sql - Can I choose what table to JOIN based on a CASE? -
for instance, if have table owner this:
+-------------------------------+ | id catid dogid fishid | +-------------------------------+ | 1 464 (null) (null) | | 2 (null) (null) 93 | +-------------------------------+
and query similar this:
select * owner join cat on owner.catid = cat.id join dog on owner.dogid = dog.id join fish on owner.fishid = fish.id;
but instead of joining every time, can use case
statement (or similar) "only join cat if value in catid column not null". possible?
each owner id
have 1 of cat, dog, or fish
(i.e. each owner, 1 not null).
no, can use left join
values:
select owner.*, coalesce(cat.col, dog.col, fish.col) col owner left join cat on owner.catid = cat.id left join dog on owner.dogid = dog.id left join fish on owner.fishid = fish.id;
you can choose (first) 1 matches in select
.
Comments
Post a Comment