2014-06-30 102 views
0

我有一張表,其中包含PRTL_BusRoute,它引用了各個區域的IDAreaID作爲ID's區域進入每個區域。選擇查詢並選擇多列,其中一列應該是不同的mssql

**ID** **BustrouteID** **AreaID** 

    0   1    3 
    1   1    5 
    1   1    6 
    2   2    5 
    3   2    6  
    4   2    8 
    5   3    9 
    6   3    12 
    7   4    1 
    8   4    8 
    9   4    11 

公交路線的名稱都存儲在tbl_BusRoute和地區都存儲在dbo.GEN_Area。我需要像這樣顯示:

Zonename1 
    Areas coming under this zone in a list 

Zonename2 
    Areas coming under this zone in a list 
........ 

我的PHP代碼是這樣的:

$area = '';                
$getbus = mssql_query("SELECT BusRouteID,AreaID FROM dbo.Acc_BusRouteDetail"); 
     while($data_getbus = mssql_fetch_row($getbus)){ 
      $getZone = mssql_query("SELECT Busroute FROM PRTL_BusRoute 
      WHERE BusRouteID = '$data_getbus[0]'"); 
      while($data_getZone = mssql_fetch_row($getZone)){ 
        $zone_name = "<h4>".$data_getZone[0]."</h4>"; 
        } 
     $getArea = mssql_query("SELECT AreaName_1 FROM dbo.GEN_Area 
      WHERE AreaID = '$data_getbus[1]' ORDER BY AreaName_1"); 
     while($data_getArea = mssql_fetch_row($getArea)){ 
      $area .= $data_getArea[0]."</br>"; 
     } 
     echo $zone_name."<br/>".$area."<br/>"; 
    } 

輸出如下:

ZoneName1 
     Areaname1 

    ZoneName1 
     AreaName1 
     AreaName2 

    ZoneName1 
     AreaName1 
     Areaname2 
     AreaName3 

    ZoneName2 
    Areaname1 

    ZoneName2 
    Areaname1 
    Areaname2 so on 

我想知道如果可能的話,我該如何選擇不同的公交路線及其下的所有區域。我用盡邏輯如何選擇單個路徑ID,然後選擇所有的區域下來

回答

1

我會稍微更改SQL查詢一次獲取所有數據,並循環和打印區域每次,如果從最後一行開始改變,則只是打印公交路線。像這樣(未經測試)的代碼;

$last_route = ''; 
$getbus = mssql_query("SELECT br.BusRoute,a.AreaName_1 FROM dbo.Acc_BusRouteDetail brd JOIN dbo.PRTL_BusRoute br ON br.busrouteid = brd.busrouteid JOIN dbo.GEN_Area a ON a.areaid = brd.areaid ORDER BY br.busroute, a.areaname_1"); 
while($data_getbus = mssql_fetch_array($getbus)){ 
    if($last_route != $data_getbus['BusRoute']) { 
     $last_route = $data_getbus['BusRoute']; 
     echo '<h4>'.$last_route.'</h4>'; 
    } 
    echo '<br/>'.$data_getbus['AreaName_1'].'</br>'; 
} 
+0

其不工作@Joachim Isaksson – Techy

+0

@Techy它有什麼問題?如果您將'SQL'查詢切換到管理工作室,是否會給出任何錯誤? –

+0

結果不顯示。控制器沒有進入while循環。我測試了sqlStudio中的sql查詢,它顯示了結果。在網頁中沒有顯示結果 – Techy