在mySql中连接多个表

时间:2013-04-23 20:14:51

标签: php mysql database

请大家帮我解释一下代码的语法

<?php
    $detail = mysql_query("SELECT O.geoLocation, O.vehicleId, O.date, OL.oCodeDescription, V.vMake, V.vModel, V.colour
                            FROM offense O, offenselist OL, vehicle V 
                            WHERE OL.oCode = O.offenseListId AND O.offenderNatId =  '$id' AND V.vehicleReg = O.vehicleId");

    while($db_field = mysql_fetch_assoc($detail)){
        $geo = $db_field['O.geoLocation'];
        $vid = $db_field['O.vehicleId'];
        $date = $db_field['O.date'];
        $offense = $db_field['OL.oCodeDescription'];                                                    
        $make = $db_field['V.vMake'];
        $model = $db_field['V.vModel'];
        $colour = $db_field['V.colour'];
        echo"   <tr><td>Date:</td><td>$date</td></tr>
                <tr><td>Offense</td><td>$offense</td></tr>
                <tr><td>Scene Location:</td><td>$geo</td></tr>
                <tr><td>Vehicle Registration No.:</td><td>$vid</td></tr>                                                        
                <tr><td>Vehicle Description:</td><td>$colour $make $model</td></tr>
                <tr><td colspan='2'>&nbsp;</td></tr>
                <tr><td colspan='2'>&nbsp;</td></tr>";

    }
?>

它返回了其中一个错误:

未定义的索引:第142行的C:\ wamp \ www \ eroad \ view.php中的O.geoLocation

2 个答案:

答案 0 :(得分:0)

您需要加入两个表之间共同的ID,例如:

$detail = mysql_query(
    "SELECT O.geoLocation, O.vehicleId, O.date, OL.oCodeDescription, V.vMake, V.vModel, V.colour
    FROM offense O 
    INNER JOIN offenselist OL 
        ON O.offenseListId = OL.oCode
    INNER JOIN vehicle V 
        ON O.vehicleId = V.vehicleReg
    WHERE O.offenderNatId = '$id'" 
);

应该这样做。

答案 1 :(得分:0)

我认为您只需输入$db_field['geoLocation'];而不是$db_field['O.geoLocation'];