【问题标题】:How to branch SQL query statement using conditions?如何使用条件分支 SQL 查询语句?
【发布时间】:2014-06-10 08:31:10
【问题描述】:

假设我们有一个表customer,列subject_type_fk。我们需要找到可以在表personenterprise 中的客户名称。 subject_type_fk 定义这两个表中的哪一个搜索。subject_type_fk 可以是 0 或 1。subject_fk 定义来自 personenterprise 的记录的主键。两个表都有我们需要检索的name 列(实际上是enterprise.enterpriseperson.last_name)。 Customer.customer 作为输入参数给出。如何为 postgreSQL 编写这种查询?


更新

【问题讨论】:

  • 你能发布表格定义吗?
  • 我个人会将CustomerPersonEnterprise 表的所有字段合并到一个表中。然后使用subject_type_fk 来确定我读取了哪些字段。
  • @Tony,你能提供你的查询版本吗?
  • @RCola - 目前你的模型不是很“关系”;正如您发现的那样,不可能在表之间创建条件关系。要关联您的表格,请决定对客户更重要的是个人还是企业。你可以有:customer 是属于enterpriseperson;或者,如果您的所有客户都是企业,则:customerenterprise,联系人是 person

标签: sql postgresql


【解决方案1】:
select p.last_name
from customer c join person p on c.subject_fk = p.person and c.subject_type_fk = 0
union    
select e.full_name
from customer c join enterprise e on c.subject_fk = e.enterprise and c.subject_type_fk = 1

(在 OP 编辑​​后编辑)

【讨论】:

    猜你喜欢
    • 2015-04-07
    • 2014-09-21
    • 1970-01-01
    • 2011-01-08
    • 1970-01-01
    • 2022-08-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多