PHP - 无法让左连接表回显

时间:2015-06-16 22:17:18

标签: php html mysql join

您好我是PHP的新手,我正在尝试加入2表并回显结果和HTML表。

这两个表是“客户端”和“作业”我想使用存储在作业表中的客户端ID以列名“client_id”来回显客户端名称。这是我的代码不确定我做错了什么。谢谢您的帮助。我愿意接受更好的方法。

        $result = mysql_query("SELECT `id`, `job_name`, `client.id`, `job_day`, `s_t`, `e_t`, `status` FROM job LEFT JOIN client ON job.client_id = client.id");
        if (!$result) {
            die("Query to show fields from table failed");
        }

        $fields_num = mysql_num_fields($result);

        echo "<table class='table table-bordered table-striped mb-none' id='datatable-tabletools' data-swf-path='assets/vendor/jquery-datatables/extras/TableTools/swf/copy_csv_xls_pdf.swf' >";
        // printing table headers
        echo "<thead>";
        echo "<th>#</th>";
        echo "<th>Job Name</th>";
        echo "<th>Client Name</th>";
        echo "<th>Job Day</th>";
        echo "<th>Start Time</th>";
        echo "<th>End Time</th>";
        echo "<th>Status</th>";
        echo "</thead>";
        // printing table rows
        while($row = mysql_fetch_row($result))
        {
            echo "<tbody>";
            echo "<tr>";

            echo "<td><a href='job_view.php?job=" . $row['0'] . "'>See</a></td>";
            echo "<td>$row[1]</td>";
            echo "<td>$row[2]</td>";
            echo "<td>$row[3]</td>";
            echo "<td>$row[4]</td>";
            echo "<td>$row[5]</td>";
            echo "<td>$row[6]</td>";

            echo "</tr>";
            echo "</tbody>";

        }
        mysql_free_result($result);
        ?>
        </table>
    </div>
</section>

2 个答案:

答案 0 :(得分:0)

你需要在ON子句周围添加括号,并指定不明确的列(确定id,也可以是其他列),并且需要在表和列周围添加反引号名称,单独(不是client.id而是clientid):

SELECT `job`.`id`, `job_name`, `client`.`id`, `job_day`, `s_t`, `e_t`, `status` 
FROM job 
LEFT JOIN client ON (job.client_id = client.id)

答案 1 :(得分:0)

SELECT `id`, `job_name`, `client`.`id`, `job_day`, `s_t`, `e_t`, `status` FROM job LEFT JOIN client ON job.client_id = client.id

为什么不选择clientid或列名称,而不是选择clientname