2012-08-31 51 views
7

我很難建立三連接查詢。MySQL三連接

我有三個表:

樓:

house ID(key) | Address | personID | 

人:

personID (key) | Name | Address | 

圖片: //房子

imageID (key) | personID | url | 

我想將結果限制爲。

我想查詢房屋地址(主),它的所有者名稱&地址,和一個所有者的圖片。

注意:每個人最多有3張圖像(圖像表中有3行),但只有一張是必要的,無論哪一張都不重要。

+2

一個人可以是多個房屋所有者?一個人行只包含一個房子ID?! 這將如何實現? – TheHe

+1

從person中刪除house_id列,而是向house表中添加owner_id列,或者更好地,使用owner_id,house_id列創建owner_house表。 – Icarus

+0

@他是我的錯,對不起,我修好了。 –

回答

19
SELECT h.Address, p.Name, p.Address as OwnerAddress, i.url FROM house AS h 
INNER JOIN person AS p ON p.personID = h.personID 
INNER JOIN images AS i ON i.personID = p.personID 
GROUP BY h.houseID 

應該爲你工作。

+0

謝謝你的幫助:) –

2

也許最好讓你使用LEFT OUTER JOIN,類似

SELECT 
    h.Address as `h_address`, 
    p.Name  as `p_name`, 
    p.Address as `p_address`, 
    i.url  as `i_url` 
FROM house AS `h` 
    LEFT OUTER JOIN person AS `p` ON (p.personID = h.personID) 
    LEFT OUTER JOIN images AS `i` ON (p.personID = i.personID) 
GROUP BY h.houseID 

它將與沒有註冊的圖像也顯示房屋。

-1

連接三個表

即:

select i_f.*, i_f_d.* , i_f_c.creator_name 
    from indent_form i_f 
    join indent_form_details i_f_d on i_f.id=i_f_d.ind_id 
    join indent_form_creator i_f_c on i_f.user_id=i_f_c.id 

indent_form table 1, 
indent_form_details table 2, 
indent_form_creator table 3,