2011-09-25 66 views
1

使用PHP,我試圖用來自MySQL數據庫中兩個不同表的數據填充HTML列表。每個表的結構如下:從多個MySQL表中加入結果並使用PHP輸出

Table: "students" 
+------------+------------+-----------+---------------+-------+ 
| student_id | first_name | last_name | city   | state | 
+------------+------------+-----------+---------------+-------+ 
| 1   | Tobias  | Funke  | Newport Beach | CA | 
+------------+------------+-----------+---------------+-------+ 
| 2   | Bob  | Loblaw | Laguna Beach | CA | 
+------------+------------+-----------+---------------+-------+ 
| 3   | Ann  | Veal  | Bland   | CA | 
+------------+------------+-----------+---------------+-------+ 


Table: "students_current" 
+------------+------------+---------------+ 
| student_id | school_id | current_class | 
+------------+------------+---------------+ 
| 1   | umass  | Sr   | 
+------------+------------+---------------+ 
| 2   | ucla  | Jr   | 
+------------+------------+---------------+ 
| 3   | ucla  | Fr   | 
+------------+------------+---------------+ 

我想只有用符合特定school_id的記錄來填充列表。

例如,如果我想要的清單隻包含學生的school_id是「加州大學洛杉磯分校」,所產生的HTML將如下所示:

<li> 
    <span class="first_name">Bob</span> 
    <span class="last_name">Loblaw</span> 
    <span class="city">Laguna Beach</span> 
    <span class="state">CA</span> 
    <span class="current_class">Jr</span> 
</li> 

<li> 
    <span class="first_name">Ann</span> 
    <span class="last_name">Veal</span> 
    <span class="city">Bland</span> 
    <span class="state">CA</span> 
    <span class="current_class">Fr</span> 
</li> 

每個<li>項目將被從綁定到特定student_id值數據庫。如何編寫將從數據庫選擇/加入適當記錄的PHP?

+1

+1對於包括鮑勃的Loblaw在SO質疑例如數據 –

回答

1

使用LEFT JOIN

SELECT * 
FROM `students` s 
    LEFT JOIN `students_current` sc ON s.`student_id` = sc.`student_id` 
WHERE `school_id` = 'ucla' 
+0

啊,我是很陌生的不同類型的連接以及何時使用它們。我一直在嘗試使用INNER JOIN,甚至沒有正確地構建它。 –

相關問題