2011-10-30 65 views
0

以下是數據庫是如何佈局的。我可以連接到數據庫。 我從數據庫中提取了兩件事,但添加了第三件,我無法讓它拉。我只需要一些幫助,如果我可以..配置如何使用mysql從3個表中提取數據

database - mmoore_drupal 

table 1 

table name = content_type_uprofile 

data 
vid= 19723 
nid =19674 
field_name_value = matthew moore 


table 2 

table name = location_instance 

data 

lid = 1521 
vid = 19723 
nid = 19674 

table 3 

table name = location 

data 

lid = 1521 
street = 
city = 
country = 
latitude = 
longitude = 

我想拉名稱,然後從其他兩個表中的其他信息。但主要是我需要從位置獲得名稱和其他信息。我想我必須有另一張桌子關聯連接。任何幫助表示讚賞。

$query = "SELECT content_type_uprofile.field_name_value,location.street,location.city 
    FROM location_instance,location,content_type_uprofile 
     WHERE location_instance.lid = location.lid and        location_instance.nid=content_type_uprofile.nid" 

$result = mysql_query($query) or die(mysql_error()); 


// Print out the contents of each row into a table 
while($row = mysql_fetch_array($result)){ 
    echo $row['nid']."-".$row['street']. " - ". $row['city']; 
    echo "<br />"; 
} 
?> 

回答

1

使用此SQL(顯式聯接語法):

SELECT 
    content_type_uprofile.nid, 
    location.street, 
    location.city 
FROM 
    content_type_uprofile 
INNER JOIN location_instance 
    ON (content_type_uprofile.nid = location_instance.nid) 
INNER JOIN location 
    ON (location_instance.lid = location.lid) 

您發佈使用implicit join SQL syntax的SQL。

我認爲,出於某種原因,我覺得在你的SQL行:

WHERE location_instance.lid = location.lid and location_instance.nid=content_type_uprofile.nid 

是從結果集中過濾掉所有行。我不確定,因爲我避免了隱式語法。

您還錯過了您的PHP代碼在結果集中查找的nid字段。

只要您的數據是正確的(即您加入的字段具有正確的值),我發佈的SQL將爲您工作。

+0

它說錯誤在第40行是結果。 –

+0

您需要將SQL粘貼到查詢工具中:http://dev.mysql.com/downloads/workbench/,http://www.quest.com/toad-for-mysql/和http:// www .phpmyadmin.net/home_page/index.php是一些受歡迎的免費軟件。這將幫助您找到錯誤。我沒有這樣做,但在校對我的SQL時,我注意到'location.city'後面有一個額外的逗號。我糾正了它。請再試一次。 – JohnB

+0

工作,並感謝新的工具。 –

-1

你曾經與join做過什麼嗎?

select *.locaition, 
    *.content_type_uprofile 
from location_instance li 
inner join location l on l.lid = li.lid 
inner join content_type_uprofile ctu on ctu.vid = li.vid 
+0

'location。*,content_type_uprofile。*' - 你讓它們顛倒。 – JohnB

相關問題