表人
ID | NAME | PHNO |ADDRESS_TYPE
1 | XXXX | 999 | HOME
2 | YYYY | 888 | OFFICE
表HOME_ADDRESS
ID PERSON_ID ADDRESS
1 | 1 | XXXXXXXXXXX
表OFFICE_ADDRESS
ID PERSON_ID ADDRESS
1 | 2 | XXXXXXXXXXX
这里我希望查询通过基于ADDRESS_TYPE加入HOME_ADDRESS和OFFICE_ADDRESS来从表PERSON获取记录,如果ADDRESS_TYPE是HOME,那么它应该从表HOME_ADDRESS获取地址详细信息其他明智的地址详细信息应来自表OFFICE_ADDRESS。
我正在使用postgresql数据库。
答案 0 :(得分:1)
这是mssql sintax,但试试这个:
select p.*, CASE WHEN p.ADDRESS_TYPE = 'HOME' THEN h.ADDRESS ELSE o.ADDRESS END from Person p
LEFT OUTER JOIN HOME_ADDRESS h on p.Id = h.PERSON_ID AND p.ADDRESS_TYPE = 'HOME'
LEFT OUTER JOIN OFFICE_ADDRESS o on p.ID = o.PERSON_ID AND p.ADDRESS_TYPE= 'OFFICE'
答案 1 :(得分:1)
来自DB-Design-Perspecitve: 也许您的数据库设计存在问题。
为什么没有一个地址表?
从技术上讲,为了达到你想要的目的,你需要做两件事:
示例:
select p.ID,
case when p.ADDRESS_TYPE = 'HOME' then ha.address else oa.address end as address
from PERSON p
left join HOME_ADDRESS ha on p.ID = ha.PERSON_ID and p.ADDRESS_TYPE = 'HOME'
left join OFFICE_ADDRESS oa on p.ID = oa.PERSON_ID and p.ADDRESS_TYPE != 'HOME'