2013-06-24 59 views
4

我有三個名爲「Guest」,「Guest_Address」和「Acutal_Address」的表。 Guest_Address是guest和acutal_address之間的鏈接表。 這是我到目前爲止。三種方式加入sql

SELECT GUEST_ADDRESS.ADDRESS_CODE,(GUEST_FNAME+' '+GUEST_LNAME) AS GUEST_NAMES 
    FROM GUEST JOIN GUEST_ADDRESS 
    ON GUEST.ADDRESS_NUM = GUEST_ADDRESS.ADDRESS_NUM; 

這隻會加入Guest和Guest_address表,但我需要加入Guest和Acutal_Address。 這是ERD。 enter image description here

回答

10

你想要做什麼是做一個額外加入到actual_address表所示:

SELECT GUEST_ADDRESS.ADDRESS_CODE,(GUEST_FNAME+' '+GUEST_LNAME) AS GUEST_NAMES 
    FROM GUEST 
    JOIN GUEST_ADDRESS ON GUEST.ADDRESS_NUM = GUEST_ADDRESS.ADDRESS_NUM 
    JOIN ACTUAL_ADDRESS ON GUEST_ADDRESS.ADDRESS_CODE = ACTUAL_ADDRESS.ADDRESS_CODE 

介意我問爲什麼你有一個鏈接表?客人可以有多個地址嗎?如果是這樣的話我會改變連接從GUEST_ADDRESS基於GUEST_ID,而不是ADDRESS_NUMGUEST如使用ADDRESS_NUM使兩個表一比一的關係,而不是一個一對多

而且之間的關係值得注意的是,如果ACTUAL_ADDRESS表中沒有地址或由於JOIN而導致GUEST_ADDRESS表中沒有地址,則上面的查詢將不會爲該來賓返回記錄。如果您希望它返回客人詳細信息,無論地址如何,只需將JOIN更改爲LEFT JOIN

2

通過輔助表GuestAddressGuestActualAddress之間存在多對多關係。所以,加盟後,一起到一組做:

select * 
from Guest 
left join GuestAddress on GuestAddress.Guest_ID = Guest.Guest_ID 
left join ActualAddress on ActualAddress.AddressCode = GuestAddress.Address_Code 

然後使用where子句可以過濾設置到一個較小的一個(子集),如果需要的話