我有一個數據庫,我住在我的客戶,我需要顯示他們按國家和城市分組和排序的頁面。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>";
}
您的查詢完好。您試圖實現的是表示層的任務,而不是SQL。 –