【问题标题】:Properly display results of mySQL one-to-many query正确显示 mySQL 一对多查询的结果
【发布时间】:2011-06-15 14:00:38
【问题描述】:

我有两张桌子:

      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,但是在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);
}
?>

【问题讨论】:

    标签: php mysql join


    【解决方案1】:
    1. 添加 order by 子句以按行程 ID 排序
    2. 创建$lastTripID 变量以检查您何时从“新行程”中获得“腿”
    3. [推荐]使用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);
        }
    

    【讨论】:

    • +1 我几乎要提交相同的答案。你打败了我:)
    • 谢谢!!我想我也需要一个更复杂的查询。这很好用! SO再次出现:)
    猜你喜欢
    • 2013-11-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-04-08
    • 1970-01-01
    • 1970-01-01
    • 2013-01-31
    • 2014-07-01
    相关资源
    最近更新 更多