开发者

Join results from multiple MySQL tables and output with PHP

Using PHP, I'm t开发者_如何学编程rying to populate an HTML list with data from two different tables in a MySQL database. The structure for each table is as follows:

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            |
+------------+------------+---------------+

I'd like to populate the list with only with records that match a specific school_id.

For example, if I want the list only to contain students whose school_id is "ucla", the resulting HTML would be as follows:

<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>

Each <li> item would be tied to a specific student_id value from the database. How do I write the PHP that will select/join the appropriate records from the database?


Using a LEFT JOIN:

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜