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