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

问题描述

|| 我有两个表:
      TRIPS
-----------------
tripID | clientID
              LEGS
--------------------------------
legID | depart | arrive | tripID
TRIPS与LEGS有一对多的关系,因为每个
tripID
有几个
legID
\。我需要以以下格式显示它们:
Trip tripID1:
    Leg legID1: depart1 - arrive1
    Leg legID2: depart2 - arrive2

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

etc...
我已经能够通过
WHILE()
循环遍历legID,但是在将LEGS循环嵌入TRIPS循环中时遇到了麻烦。我的查询是:
<?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);
}
?>
    

解决方法

         添加
order by
子句以按旅行ID排序 创建
$lastTripID
变量以检查何时从“新行程”获得“腿” [推荐]使用
join
从多个表中选择数据 码:
<?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);
    }
    

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...