我有3张桌子:
PeopleAffiliation: Affiliationid, peopleid, addressid
Addresses: addressid, addresstypeid, address, city, state, zip, preferredaddress (bit)
AddressTypes: addresstypeid, addresstypeconst
我需要选择地址为首选地址的所有人员地址,但如果没有首选地址,那么我必须显示地址,其中addresstypeconst ='工作'
我无法弄清楚如何做到这一点。有谁知道我怎么能做到这一点?
以下是我想要完成的一个示例:
1 1 1
2 1 2
3 2 3
4 2 4
1 3 1
2 5 0
3 1 0
4 5 0
1 Home
2 mail
3 shipping
5 Work
1 1 1
4 2 4 (showing work address as user doesn't have a preferred one)
答案 0 :(得分:0)
这应该做:
SELECT *
FROM peopleaffiliation pa
LEFT OUTER JOIN addresses addr
ON pa.addressid = addr.addressid
LEFT OUTER JOIN addresstypes addtyp
ON addtyp.addresstypeid = addr.addresstypeid
WHERE (addr.preferredaddress = 1 )
OR( COALESCE(addr.preferredaddress, 0) = 0
AND addtyp.addresstypeconst = 'Work' )