简体   繁体   English

从几列中选择不同的

[英]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. 我想返回一个城市行,而不是所有与所有zip关联的行。 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. 我想返回以“ Colo”开头的前5个城市名称,但只有1个科罗拉多斯普林斯。

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. 仅在使用聚合函数时使用GROUP BY Use DISTINCT instead 改用DISTINCT
  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 使用ORDER BY可以确保每次执行查询时都返回一致的结果

My recommendation: 我的建议:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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