我正在制作类似手风琴的菜单。我想在多列中GROUP BY
。我研究过但没有运气。我将打破目前的结构:
在我的数据库中,我有重复country
个条目和city
个条目。结构看起来像这样(较小的例子):
| ID | Country | City |
________________________________
| 1 | Sweden | Stockholm |
| 2 | Sweden | Stockholm |
| 3 | Sweden | Lund |
| 4 | Sweden | Lund |
| 5 | Germany | Berlin |
| 6 | Germany | Berlin |
| 7 | Germany | Hamburg |
| 8 | Germany | Hamburg |
使用GROUP BY
我可以在循环中停止重复相同的VALUE
,这是我用于此的代码:
$stmt = $db->query('SELECT country FROM table GROUP BY country');
虽然这很有效。现在我想抓住City
并将值放在我的手风琴下拉,同时不重复这些条目。这是我目前的代码(我正在使用bootstrap collapse for accordion effect):
<ul class="retailers-list"> // list
<?php
$stmt = $db->query('SELECT country, city FROM retailers GROUP BY country');
while($row = $stmt->fetch(PDO::FETCH_ASSOC)) :
$country = $row['country'];
$city = $row['city']; ?>
<li>
<a data-pjax="content" data-toggle="collapse" data-target="#<?= $country ?>" href="retailers.php?country=<?= $country ?>">
<?= $country ?></a></li> //lists all countries not repeating
<div id="<?= $country ?>" class="collapse in">
<a data-pjax="content" href="retailers.php?city=<?= $city ?>">
<?= $city ?></a><br> // listing only 1 city at a time
</div>
<? endwhile ?>
</ul>
我遇到的问题是它只有echo的一个值,所以它只会回应斯德哥尔摩,它不会回显Lund或任何其他值。我想这是因为GROUP BY国家造成的,那么GROUP BY国家和其他价值是否可能?
编辑(所需的HTML输出):
Sweden
> Stockholm
> Lund
Germany
> Berlin
> Hamburg
使用DISTINCT,输出看起来像这样,这不是我想要的:
Sweden
> Stockholm
Sweden
> Lund
Germany
> Berlin
Germany
> Hamburg
答案 0 :(得分:0)
只需在GROUP BY中添加城市:
SELECT country, city FROM retailers GROUP BY country, city
答案 1 :(得分:0)
因此,您需要为每个国家/地区提供相关城市的明确列表 如果您的结果集在城市:国家/地区比例不大,您可以使用:
SELECT country, GROUP_CONCAT(DISTINCT city) FROM retailers GROUP BY country
回应结果以了解它是如何工作的。
如果结果集是大城市:国家/地区比率,您可以直接执行
SELECT country, city FROM retailers GROUP BY country,city
OR
SELECT DISTINCT country, city FROM retailers ORDER BY country,city
答案 2 :(得分:0)
嗯,我对PDO太愚蠢,但粗略的程序方法可能看起来像这样......
SELECT * FROM cities2;
+---------+------------+---------+---------+---------+
| city_id | city_name | lat | lon | country |
+---------+------------+---------+---------+---------+
| 1 | New York | 40.6700 | 73.9400 | US |
| 2 | London | 51.5072 | 0.1275 | UK |
| 3 | Kodiak | 45.0000 | 29.0000 | US |
| 4 | Birmingham | 34.0000 | 45.0000 | US |
| 5 | Birmingham | 52.2900 | 1.5400 | UK |
+---------+------------+---------+---------+---------+
<?php
include('../testi.inc');
$query = "
SELECT DISTINCT country,city_name FROM cities2 ORDER BY country,city_name;
";
$result = mysqli_query($db,$query);
$country = '';
while($rows = mysqli_fetch_assoc($result)){
if ($country == $rows['country']){
echo " >".$rows['city_name']."<br>\n";
} else {
echo $rows['country']."<br>\n >".$rows['city_name']."<br>\n";
$country = $rows['country'];
}
} // end of while loop
?>
输出:
UK<br>
>Birmingham<br>
>London<br>
US<br>
>Birmingham<br>
>Kodiak<br>
>New York<br>