2014-03-24 48 views
1

我有一個選擇查詢和插入查詢,如下所示:PHP/MySQL的選擇查詢,要經過四個相關表中數據庫

$select_query = mysql_query("SELECT trees, animals FROM Table1 WHERE gardens > '10000'", $mysql_connection); 
while ($row = mysql_fetch_array($select_query)) { 
$trees = $row['trees']; 
$animals = $row['animals']; 
$names = ?????????? // in order to get the names, a select query should go through Table2 and Table4 
//and finally get the assigned names from Table3. Please see the schematic picture of tables. 
$insert_query = mysql_query("INSERT INTO table6 (new_trees, new_animals, new_name) VALUES ('$trees', '$animals', '$names')", $mysql_connection); } 

我想選擇和插入$trees$animals$names到另一個表。 $trees$animals變量沒有問題,但我不知道如何選擇$names的數據。如表格的示意圖所示,Table1.id=Table2.referenceTable2.first_idTable4.id獲得值。

然後,從Table4.second_id得到Table3.id值和最後Table3.name必須以滿足在上述$insert_query$names變量被選擇。對不起,如果我沒有更清楚地解釋問題。您能否請回顧照片並讓我知道您的解決方案?

schematic illustration of picture

+0

這個方案看起來像一個很好謎! –

回答

2

查找的JOIN條款:

SELECT 
    t1.id, t1.trees, t1.animals, t3.name 
    FROM table1 AS t1 
    LEFT JOIN table2 AS t2 
    ON t2.reference = t1.id 
    LEFT JOIN table4 AS t4 
    ON t2.first_id = t4.id 
    LEFT JOIN table3 AS t3 
    ON t4.second_id = t3.id 

    WHERE // Your select conditions 
+0

優秀,您的答案完美無瑕,謝謝。 – Sami

+0

你幾乎給出了你的計劃的答案。我只是用'JOIN'來粘貼這些作品;-) – svvac

+0

我剛剛畫出了這張照片::)),再次感謝,歡呼聲 – Sami