正确显示mySQL一对多查询的结果

时间:2011-06-15 14:00:38

标签: php mysql join

我有两张桌子:

      TRIPS
-----------------
tripID | clientID

              LEGS
--------------------------------
legID | depart | arrive | tripID

TRIPS与LEGS有一对多的关系,因为每legID有几个tripID个。{我需要以下列格式显示它们:

Trip tripID1:
    Leg legID1: depart1 - arrive1
    Leg legID2: depart2 - arrive2

Trip tripID2:
    Leg legID3: depart3 - arrive3
    Leg legID4: depart4 - arrive4

etc...

我已经能够通过WHILE()循环遍历legIDs,但是我在TRIPS循环中嵌入LEGS循环时遇到了麻烦。我的疑问是:

<?php
$legsQuery = "SELECT  trips.tripID, legs.depart, legs.arrive FROM legs, trips WHERE `trips`.tripID = `legs`.tripID";
$legsQueryResult = mysql_query($legsQuery) or die("QUERY LEG ERROR: " . mysql_error());
while($row = mysql_fetch_assoc($legsQueryResult)) {
    print_r($row);
}
?>

1 个答案:

答案 0 :(得分:1)

  1. 添加order by子句以按行程ID排序
  2. 创建$lastTripID变量以检查何时从“新旅行”获得“腿”
  3. [推荐]使用join从多个表中选择数据
  4. 代码:

    <?php
        $legsQuery = "
            select  
                trips.tripID, 
                legs.depart, 
                legs.arrive 
            from 
                legs
                inner join trips on trips.tripID = legs.tripID
            order by
                trips.tripID
        ";
        $legsQueryResult = mysql_query($legsQuery) or die("QUERY LEG ERROR: " . mysql_error());
        $lastTripID = null;
        while ($row = mysql_fetch_assoc($legsQueryResult)) {
            if ( $row['tripID'] !== $lastTripID ) {
                echo $row['tripID'], "\n";
                $lastTripID = $row['tripID'];
            }
            print_r($row);
        }