我正在编写一个查询,我需要选择母公司,如果它存在,如果母公司不存在,第二公司存在,我需要选择它,如果两者都不存在那么我需要选择公司(儿童公司)。
鉴于公司表中有ID和公司名称。
还有一个Movie表,其中包含以下列:
我如何创建一个查询呢?
请帮助!!
答案 0 :(得分:0)
您可以在查询中使用case语句来匹配您的逻辑。我认为这应该很接近:
select m.id,
case
-- has both, use child
when p.id is not null and s.id is not null then m.company
-- has parent not second, use parent
when p.id is not null and s.id is null then p.company
-- has second not parent, use second
when p.id is null and s.id is null then p.company
-- has neither, not sure what you want to do
when p.id is null and s.id is null then 'None'
end as company
from movies as m
left join companies as s
on m.second_company_id = s.id
left join companies as p
on m.parent_company_id = p.id