PHP MySqli GROUP BY

时间:2015-10-26 16:56:41

标签: php mysqli

我有一个数据库,我可以容纳我的客户,我需要在按州和城市分组和订购的页面上显示它们。

如果我使用下面的代码,我会得到我想要的结果,但是每个城市的州都是重复的。 如果我将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>";
}

1 个答案:

答案 0 :(得分: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 运算符将所有行折叠为单行,因为它们与参数匹配。为避免将所有记录折叠成一行,您只需根据需要向该运算符添加更多字段。