我正在研究類似菜單的手風琴。我正在嘗試GROUP BY
多欄。我已經研究過,但沒有運氣。我將打破我目前的結構: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
,並將手風琴中的值放下,同時不要重複這些條目。這裏是我當前的代碼(我用引導崩潰手風琴效果):
<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>
我遇到的問題是,它只能隨聲附和的一個值,所以它只能隨聲附和斯德哥爾摩,它不會回聲隆德或任何其他值。我想這是由於GROUP BY國家造成的,所以GROUP BY國家和另一個價值可能嗎?
EDIT(所需的HTML輸出):
Sweden
> Stockholm
> Lund
Germany
> Berlin
> Hamburg
使用DISTINCT輸出這個樣子的,這不是我所期待的:
Sweden
> Stockholm
Sweden
> Lund
Germany
> Berlin
Germany
> Hamburg
我不知道你想達到什麼。你能顯示所需的HTML輸出嗎? – SirDarius
在沒有任何聚合函數的情況下,使用GROUP BY是不恰當的(並且很可能是低效的)。改用DISTINCT運算符。 – Strawberry
@Strawberry請參閱編輯,謝謝 – SethCodes