【问题标题】:Oracle: What is the best way to use two tables in a mutually exclusive way?Oracle:以互斥方式使用两个表的最佳方式是什么?
【发布时间】:2015-04-30 01:22:54
【问题描述】:

我有以下示例查询

select a.name,c.company
from employee a, company c 
where a.comp_id = c.comp_id
and a.active='Y'

现在我有两个新表

company_profile,(每家公司的资料值。每家公司可能有也可能没有此表中的数据)

profile_defaults(包含独立于公司的每个配置文件项的默认配置文件值)

现在我需要参考特定公司的 company_profile 中的“show_data”列。如果该公司没有行,那么我需要从 profile_defaults 表中获取值。我如何以最好的方式将这个逻辑集成到我上面提到的第一个查询中。

表格


员工

|名称|Comp_id|活动|

公司

|Comp_id|名称|

公司简介

|comp_profile_id|profile_id|comp_id|profile_name|profile_value|

Profile_Defaults

|profile_id|profile_name|profile_value|

还有很多其他的表被使用。但我现在只为这个案例缩短了四张桌子。

【问题讨论】:

  • LEFT JOIN 两个新表并使用 COALESCE()(或 NVL()),如果您更喜欢 Oracle 特定的)。

标签: sql oracle


【解决方案1】:

尝试使用此查询:

SELECT a.name, c.company, NVL(cp.profile_value, pd.profile_value)
FROM employee a INNER JOIN company c
ON a.comp_id = c.comp_id
LEFT JOIN company_profile cp
ON c.comp_id = cp.comp_id
LEFT JOIN profile_defaults pd
ON cp.profile_id = pd.profile_id

此解决方案假定您在 company_profile 和默认 profile_defaults 表中都有列 comp_id,您可以将给定公司的记录加入到这些列中。正如@PM77-1 提到的,我使用NVL() 首先检查company_profile 表,如果前者没有找到,则默认使用profile_defaults

【讨论】:

  • 只是为了澄清蒂姆。公司 ID 的值将不会作为 profile_defaults 表的一部分提供。如果它具有公司价值,我必须使用另一个名为 profile_id 的列从 company_profile 获取确切值,或者我必须使用 profile_defaults 表中的默认值
  • profile_defaults中的哪一列是您将从公司加入给定记录的?
  • 已添加有问题的示例表架构。如果是company_profile,我需要检查comp_id 和特定的profile_id。如果是profile_defaults,我只需要检查profile_id
猜你喜欢
  • 1970-01-01
  • 2011-05-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-02-28
相关资源
最近更新 更多