简体   繁体   中英

select distinct from several columns

I've a table of cities, states and zips, but as you know some cities have multiple zip codes. I want to return one of the city rows, not all associated with all zips. This is for predictive text input.

cities2 Table example
Colorado Springs | CO | 80910 | Colorado Springs, CO
Colorado Springs | CO | 80911
Colorado Springs | CO | 80912

{
$result = mysql_query("SELECT * FROM `cities2` WHERE `city` LIKE '$city%' LIMIT 5");
    while($row = mysql_fetch_array($result))
    $cities[] = $row['city'];
}

I would like to return the first 5 city names that start with "Colo" but only 1 colorado springs.

I hope I explained that well.

you just need a group by

SELECT * FROM `cities2` WHERE `city` LIKE '$city%' GROUP BY city LIMIT 5

you can group by what ever column you want to be distinct.

SELECT * 
  FROM cities2 
   WHERE city 
    LIKE '$city%' 
      GROUP BY city 
        LIMIT 5 

From my soapbox:

  1. Only use GROUP BY when using aggregate functions. Use DISTINCT instead
  2. Explicitly state the columns you want returned, not *.
  3. Use an ORDER BY to ensure consistent results are returned every time the query is executed

My recommendation:

SELECT DISTINCT city
FROM cities2
WHERE city like '$city%'
ORDER BY city 
LIMIT 5;

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