2011-06-15 79 views
2

我有兩個表:正常顯示的MySQL結果一個一對多查詢

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

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

TRIPS在與腿一個一對多的關係,有幾個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環內腿循環。我的查詢是:

<?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
  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); 
    } 
+0

+1我幾乎要提交相同的答案。你擊敗了我:) – 2011-06-15 14:11:06

+0

謝謝!我想我還需要一個更復雜的查詢。這很好! SO再次通過:) – 2011-06-15 14:40:13