如何使用条件分支SQL查询语句?

时间:2014-06-10 08:31:10

标签: sql postgresql

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


更新

enter image description here

1 个答案:

答案 0 :(得分: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编辑后编辑)