Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/sql-server-2008/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Sql server 条件联接/备用选择_Sql Server_Sql Server 2008 - Fatal编程技术网

Sql server 条件联接/备用选择

Sql server 条件联接/备用选择,sql-server,sql-server-2008,Sql Server,Sql Server 2008,我正在编写一个查询,其中我需要选择一个母公司(如果存在),如果母公司不存在,第二个公司存在,我需要选择该公司,如果两者都不存在,那么我需要选择公司(子公司) 假设有一个带有ID和公司名称的公司表 还有一个具有以下列的电影表: ID(指电影ID) 引用的母公司列(公司表中的ID#) 参考的第二家公司(公司表中的ID) 公司(子公司名称) 我将如何创建这样做的查询 请帮忙 您可以在查询中使用case语句来匹配逻辑。我认为这应该很接近: select m.id, case

我正在编写一个查询,其中我需要选择一个母公司(如果存在),如果母公司不存在,第二个公司存在,我需要选择该公司,如果两者都不存在,那么我需要选择公司(子公司)

假设有一个带有ID和公司名称的公司表

还有一个具有以下列的电影表:

  • ID(指电影ID)
  • 引用的母公司列(公司表中的ID#)
  • 参考的第二家公司(公司表中的ID)
  • 公司(子公司名称)
我将如何创建这样做的查询


请帮忙

您可以在查询中使用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

为什么不把m.company也放在coalesce表达式中,即coalesce(s.company_name,p.company_name,m.company,'None')@rivarle-最初,我误读了OPs要求。我必须完全重新编写查询,因为合并不起作用。