2015-10-26 55 views
0

我有一個數據庫,我住在我的客戶,我需要顯示他們按國家和城市分組和排序的頁面。PHP MySqli GROUP BY

如果我使用下面的代碼,我會得到我想要的結果,但州政府會爲每個城市重複。 如果我將ORDER BY更改爲GROUP BY,那麼它只顯示1個結果,該州有幾個城市,我顯然希望它們都在相關州下列出。

任何幫助,歡迎。

"SELECT state, city, company_name FROM mytable WHERE status='T' AND city <>'Head Office' AND company_name <>'my company' ORDER BY state ASC" 

如下要求進一步代碼:

$coverage=""; 
$sql = "SELECT state, city, company_name FROM mutable WHERE status='T' AND city <>'Head Office' AND company_name <>'my company' GROUP BY state, city ORDER BY state ASC, city ASC"; 
$result = mysqli_query($conn, $sql); 
if (mysqli_num_rows($result) > 0) { 
$currentCity = NULL; 
while($row = mysqli_fetch_assoc($result)) { 
    $id = $row["id"]; 
    $state =$row["state"]; 
    $office = $row["city"]; 
    $agent = $row["company_name"]; 
    if($row["city"] !== $currentCity) { 
     $currentCity = $row["city"]; 
     $coverage .= ' 
     <div id="stateCoverage" class="fluid "> 
     <p><strong class="white">' . $state . '</strong></p> 
     </div> 
      <div id="officeCoverage" class="fluid "> 
       <h3>' . $office . '</h3> 
      </div> 
     '; 
    } 
    $coverage .= ' 
     <div id="imageCoverage" class="fluid "> 
       <img src="http://foo/bar/logos/' . $agent . '.jpg" alt="' . $agent . '"> 
      </div> 
    '; 

} 
}else{ 
$coverage="<p>There seems to have been a problem locating your content, please try again, if the problem persists we would be grateful if you reported it to us, Thank you.</p>"; 
} 
+2

您的查詢完好。您試圖實現的是表示層的任務,而不是SQL。 –

回答

0

你可能尋找它查詢的這個各種各樣的東西:

SELECT 
    state, city, company_name 
FROM 
    mytable 
WHERE 
    status = 'T' AND city <> 'Head Office' 
    AND company_name <> 'my company' 
group by state, city, company_name 
ORDER BY state ASC, city ASC, company_name ASC 

GROUP BY操作摺疊所有行成一行,因爲它們與參數匹配。爲了避免將所有記錄摺疊成一行,只需要將更多字段添加到該運算符中即可。

+0

但他每個城市仍然會有一行,即重複的狀態值。 –

+0

謝謝@jimmy是的,我嘗試了所有的參數,我仍然得到重複,這就像我需要拆分查詢,在國家將不會有重複,但可能在城市,所以我不能實現任何與DISTINCT即使這基本上是我想要的DISTINCT(State) –

+0

@IanPither如前所述,這不是可以(或應該)在SQL中完成的事情。 –