group_concat问题,需要唯一

时间:2013-10-28 15:02:29

标签: php mysql pdo

我从MYSQL中提取数据并使用GROUP_CONCAT和AS。

<ul class="retailers-list">
<?  
$query = "SELECT id, country, group_concat(DISTINCT city SEPARATOR '<br>') AS city, country FROM retailers GROUP BY country";
$stmt = $db->query($query);
while($row = $stmt->fetch(PDO::FETCH_ASSOC)) :
?>
<li>
<a href="search.php?country=<?= $row['country']; ?>"><?= $row['country']; ?></a>
<br>
<a href="search.php?city=<?= $row['city']; ?>">
<?= $row['city']; ?></a> //group_concat / AS
</li>   
<?  endwhile ?>     
</ul>

问题是输出是一个链接。它似乎将所有城市价值分组为$ row ['city'] ;.如何让每个城市拥有自己独特的链接,我需要使用group_concat和AS,并为每个城市提供自己唯一的URL。

相关文章:Listing issue, GROUP mysql

2 个答案:

答案 0 :(得分:1)

这是我的解决方案!解决!

<ul class="retailers-list">
<?  
$query = "SELECT id, country, group_concat(DISTINCT city) AS city, country FROM retailers GROUP BY country";
$stmt = $db->query($query);
while($row = $stmt->fetch(PDO::FETCH_ASSOC)) :
?>
<li>
<a data-pjax="content" data-toggle="collapse" data-target="#<?= $row['id']; ?>" href="retailers.php?country=<?= $row['country']; ?>">
<?= $row['country']; ?></a>


<div id ="<?= $row['id']; ?>" class="collapse in">
<?php 
  $cities = explode(',',$row['city']);
  foreach ($cities as $city) {
?>
    <a data-pjax="content" href="retailers.php?city=<?= $city ?>"><?= $city; ?></a><BR>
<?php
  }
?>
</div>
</li> 
<?  endwhile ?> 

答案 1 :(得分:1)

简而言之,您应该选择最简单的查询:

SELECT id, country, city FROM retailers GROUP BY country ORDER BY country

请注意,您没有按国家/地区订购结果,而且根据您的问题,这似乎是必须的。

然后你基本上执行(我认为在英语中称为a)流量控制切割。也就是说,您将获得如下结果:

Country   | City
----------+-------------
Argentina | La Plata
Argentina | Buenos Aires
USA       | New York
USA       | Los Angeles
Brazil    | Sao Paulo

所以你基本上需要2个循环(每个嵌套级别一个循环)。一个用于区分国家,一个用于输出一个国家的所有不同城市。在伪php代码中:

row = get_next_result
while (row) {           // while there are still elements to be fetched
  current_country = row[country]
  while (row && current_country == row[country]) {
    output current_country and row[city]
    row = get_next_result
  }
}

我将PHP的翻译留给你......但这是99%的工作:P