简体   繁体   中英

Sql SELECT group by and order

mI have a database with 2 columns, CITY and REGION. I want to populate my form select input and group them by region.

I am using Bootstrap 3 and i want to add optgroup to the select input, with the region name for each region I have, and all the cities to follow, if this make sense.

Something like this:

 <optgroup label="region 1"> <option>city 1</option> <option>city 2</option> <option>city 3</option> <option>......</option> </optgroup> <optgroup label="region 2"> <option>city 1</option> <option>city 2</option> <option>city 3</option> <option>......</option> </optgroup> <optgroup label="region 3"> <option>city 1</option> <option>city 2</option> <option>city 3</option> <option>......</option> </optgroup> 

the question is: how should I do the sql select to get what I want? And to have them sorted alphabetically, the regions and the cities.

One way is to use group_concat()

select 
region,
group_concat(city order by city) as cities
from table_name 
group by region
order by region

The above query will give you all the region name and the cities as comma seperated something as

region1 city1,city2,city3
.....

So while you loop through the records you can have the regionname and then split the comma separated cities as an array and by looping through the array can generate the options.

In PHP it could be done as

$conn = new PDO('mysql:host=localhost;dbname=your_db_name', 'user_name', 'password');
$qry = 'select 
    region,
    group_concat(city order by city) as cities
    from table_name 
    group by region
    order by region';
$stmt = $conn->prepare($qry);
$stmt->execute();
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
   echo '<optgroup label="'.$row['region'].'">';
   $cities = explode(",",$row['cities']);
   foreach($cities as $city){
    echo '<option>'.$city.'</option>';
   }
   echo '</optgroup>';
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM