简体   繁体   中英

How to write query to join table A to table B OR C based on table A one column value?

Table PERSON

ID | NAME   | PHNO |ADDRESS_TYPE
1  |  XXXX  |  999 |   HOME
2  |  YYYY  | 888   | OFFICE

Table HOME_ADDRESS

ID PERSON_ID ADDRESS
1  | 1      | XXXXXXXXXXX

Table OFFICE_ADDRESS

ID PERSON_ID ADDRESS
1  | 2      | XXXXXXXXXXX

Here I want query to get record from table PERSON by joining HOME_ADDRESS and OFFICE_ADDRESS based on ADDRESS_TYPE, if ADDRESS_TYPE is HOME then it should get address details from table HOME_ADDRESS other wise address details should come from table OFFICE_ADDRESS.

I am using postgresql database.

it's mssql sintax, but try this:

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'

From the DB-Design-Perspecitve: Maybe there is a Problem with your Database-Design.

Why isn't there one Address-Table?

Technically there are two things you need to do in order to achieve what you want:

  1. Left-Join both Address-Tables
  2. In the select-clause use CASE ... WHEN ... THEN ... ELSE ... END to conditionally use the right address-type.
    For Details see the PostgreSQL-Documentation

Example:

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'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM