左侧连接2列

时间:2015-04-13 09:34:19

标签: php mysql join

您好我有2张桌子。 tbl_recordstbl_guards。在tbl_guards我有guard_id,在tbl_records我有guard_idguard_id_in。这是我目前的代码:

try
    {
    $stat = "0";
    $query = "SELECT rec.*, tbl_guard.fname, tbl_guard.lname
FROM tbl_records as rec
LEFT JOIN tbl_guard ON tbl_guard.guard_id = rec.guard_id
LEFT JOIN tbl_records ON tbl_records.guard_id_in = tbl_guard.guard_id
    WHERE rec.stud_id=? AND rec.status=?";

    $stmt  = $dbc->prepare($query);
    $stmt->bindParam(1, $_GET['id']);
    $stmt->bindParam(2, $stat);
    $stmt->execute();
    echo "<table cellpadding='3' class='searchTbl'>";
    echo "<thead>";
    echo "<tr>";
    echo "<th>Actual Date</th>";
    echo "<th>Purpose</th>";
    echo "<th>Destination</th>";
    echo "<th>Exact TO</th>";
    echo "<th>Expected TI</th>";
    echo "<th>Guard</th>";
    echo "<th>Actual TI</th>";
    echo "<th>Guard IN</th>";
    echo "</tr>";
    echo "</thead>";
    while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
        extract($row);
        $guard = $fname . " " . $lname;
        echo "<tbody>";
        echo "<tr>";
        echo "<td>$act_date</td>";
        echo "<td>$purpose</td>";
        echo "<td>$destination</td>";
        echo "<td>$exact_timeout</td>";
        echo "<td>$exp_timein</td>";
        echo "<td>$guard</td>";
        echo "<td>$act_timein</td>";
        echo "<td>$guard</td>";
        echo "</tr>";
        echo "</tbody>";
        }
    }
catch (PDOException $e)
    {
    echo "Error: " . $e->getMessage();
    }
echo "</table>";

Heretbl_records个数据。 heretbl_guard个数据。 Here是当前的输出。

我的问题是它在我的代码中guard_idguard_id_in显示相同的警卫。

5 个答案:

答案 0 :(得分:4)

您可以多次使用LEFT JOIN,例如:

SELECT tbl_records.*, tbl_guard.fname, tbl_guard.lname
FROM tbl_records as rec
LEFT JOIN tbl_guard ON tbl_guard.guard_id = rec.guard_id
LEFT JOIN tbl_records ON tbl_records.guard_id_in = tbl_guard.guard_id

答案 1 :(得分:2)

You can use:

SELECT tbl_records.*, tbl_guard.fname, tbl_guard.lname 
FROM tbl_records 
LEFT JOIN tbl_guard ON (tbl_records.guard_id OR tbl_records.guard_id_in) = tbl_guard.guard_id

答案 2 :(得分:1)

为了确保,您的tbl_records表可以通过guard_id和guard_id_in链接到两个不同的tbl_guards?

也许你可以试试:

SELECT tbl_records.*, tbl_guard.fname, tbl_guard.lname FROM tbl_records LEFT JOIN tbl_guard ON tbl_guard.guard_id IN (tbl_records.guard_id, tbl_records.guard_id_in)

答案 3 :(得分:1)

SELECT tr1。*,tg1fnametg2。lname 来自tbl_records AS tr1 LEFT JOIN tbl_guard AS tg1 ON tg1guard_id = tr1guard_id, LEFT JOIN tbl_guard AS tg2 ON tg2guard_id = trlguard_id_in

答案 4 :(得分:1)

您应该选择保护表的两倍并为字段使用别名:

SELECT tr1.*, tg1.fname AS FNAME, tg1.lname AS LNAME, 
       tg2.fname AS FNAME_IN, tg2.lname AS LNAME_IN 
FROM tbl_records AS tr1 
LEFT JOIN tbl_guard AS tg1 
     ON tg1.guard_id = tr1.guard_id, 
LEFT JOIN tbl_guard AS tg2 
     ON tg2.guard_id = trl.guard_id_in

然后在PHP中你会有更多变量:$ FNAME,$ LNAME,$ FNAME_IN,$ LNAME_IN