例如,如果我有一个像这样的表OWNER:
+-------------------------------+ | ID CatID DogID FishID | +-------------------------------+ | 1 464 (null) (null) | | 2 (null) (null) 93 | +-------------------------------+
和类似的查询:
select *
from owner
join cat
on owner.catid = cat.id
join dog
on owner.dogid = dog.id
join fish
on owner.fishid = fish.id;
但是,我不是每次都加入,而是使用CASE
语句(或类似名称)来说明“只有在CatID列中的值不为空”时才加入CAT。这可能吗?
每个所有者ID
只有cat, dog, or fish
中的一个(即对于每个所有者,只有一个不为空)。
答案 0 :(得分:3)
不,但您可以使用left join
,以便获得所有值:
select owner.*, coalesce(cat.col, dog.col, fish.col) as col
from 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;
然后,您可以选择select
中匹配的(第一个)。
答案 1 :(得分:1)
我选择了3个左连接,并确保每个animal.id都有一个索引,但你可以试试像这样的联盟:
select *
from owner join cat on owner.catid = cat.id
where owner.catid is not null
union all
select *
from owner join dog on owner.dogid = dog.id
where owner.dogid is not null
union all
select *
from owner join fish on owner.fishid = fish.id
where owner.fishid is not null;
我非常怀疑它会更快