使用PHP连接多个MySQL表和输出的结果

时间:2011-09-25 21:54:56

标签: php mysql html join

使用PHP,我正在尝试使用MySQL数据库中两个不同表的数据填充HTML列表。每个表的结构如下:

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为“ucla”的学生,则生成的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 个答案:

答案 0 :(得分:1)

使用LEFT JOIN

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