简体   繁体   中英

Group together similar entries in the query in MySQL

I want to group together the Airports that share the same 'city' column. Right now they're all listed side by side which is good, but I want to add an extra option tag for each city that has two airports.

For example right now my code shows:

New York - JFK

New York - La Guardia

Los Angeles - LAX

But I want it to show:

New York - All

New York - JFK

New York - La Guardia

Los Angeles - LAX

Any help is appreciated. Thanks in advance

$getairportsfrom=mysqli_query($db,"SELECT * FROM details WHERE type='Airport' ORDER BY city");

                   while($rowfrom = mysqli_fetch_array($getairportsfrom)) {
               echo "<option value='".$rowfrom['title']."'>" . $rowfrom['city'] . " - " . $rowfrom['title'] . "</option>";
                   }

If this is your query:

SELECT city, title
FROM details
WHERE type = 'Airport'
ORDER BY city;

You can get what you want with this query:

select city, title
from ((select city, 'All' as title, 1 as ordering
       from details
       group by city
       having count(*) > 1
      ) union all
      (select city, title, 2 as ordering
       from details
      )
     ) d
order by city, ordering;

SQL isn't really designed for this type of manipulations for presentation. However, it is possible to do this.

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