2010-01-12 59 views
0

海傢伙,MySQL的加入兩個表來獲取記錄

我有兩個表Incharge財產。我的物業表有三個字段1stIncharge,2ndIncharge和3rdIncharge。 InchargeId被設置爲在屬性表中的所有上述領域外鍵..

如何編寫連接兩個表中的select語句。我已經盡力了一點,但沒有結果

select P.Id,P.Name,P.1stIncharge,P.2ndIncharge,P.3rdIncharge,I.Id from 
Property as P join Incharge as I where (\\How to give condition here \\) 

人3場P.1stIncharge,P.2ndIncharge,P.3rdIncharge有外鍵I.Id

編輯:

select P.Id,P.Name,P.1stIncharge,P.2ndIncharge,P.3rdIncharge,I1.Id from 
Property as P 
inner join Incharge as I1 on I1.Id=P.1stIncharge 
inner join Incharge as I2 on I2.Id=P.2ndIncharge 
inner join Incharge as I3 on I3.Id=P.3rdIncharge 

and this query working 
+0

@Saranya:如果Codesleuth的解決方案不是您想要的,請考慮編輯您的問題並提供有關預期結果的示例數據。 – 2010-01-12 12:17:34

回答

0

我不知道關於這兩個表的外鍵的名字,但我認爲你正在尋找這樣的:

SELECT P.Id, P.Name, P.1stIncharge, P.2ndIncharge, P.3rdIncharge, I.Id 
FROM Property as P INNER JOIN Incharge as I ON P.InchargeId = I.Id 
+0

@Codesleuth 3字段P.1stIncharge,P.2ndIncharge,P.3rdIncharge具有外鍵I.Id – Saranya 2010-01-12 12:02:36

+0

@Codesleuth沒有字段名爲P.InchargeId – Saranya 2010-01-12 12:03:36

+0

對不起,但您的問題有點含糊。我很高興你對它進行了排序。 – Codesleuth 2010-01-12 13:21:05

0

如果你的表和列名是正確的,你提供的解決方案看起來不錯(我重新格式化它):

SELECT 
    P.Id, P.Name, P.1stIncharge, P.2ndIncharge, P.3rdIncharge, 
    I1.Id 
FROM Property AS P 
JOIN Incharge AS I1 ON (I1.Id = P.1stIncharge) 
JOIN Incharge AS I2 ON (I2.Id = P.2ndIncharge) 
JOIN Incharge AS I3 ON (I3.Id = P.3rdIncharge) 

你會得到什麼樣的錯誤?