MySQL的一些列不同

时间:2012-04-07 05:25:21

标签: mysql

我有以下查询,效果很好。

 SELECT DISTINCT city,region1,region2 from static_geo_world where country='AU' AND
 (city LIKE '%geel%' OR region1 LIKE '%geel%' OR region2 LIKE '%geel%' OR region3 LIKE '%geel%' OR zip LIKE 'geel%') ORDER BY city;

我还需要提取一个名为“id”的列,但这会弄乱DISTINCT,因为每个ID都不同。

如何获得与上述相同的UNIQUE记录集,同时获取每条记录的“id”? 注意:有时我可以返回几千条记录,因此无法查询每条记录。

任何想法都会非常受欢迎......

示例:

表可能包含以下内容

 ID Country zip  region1        region2  region3 City
 1  AU      3323 geelong        victoria         Geelong
 2  AU      3324 geelong        victoria         Geelong
 3  AU      3325 Geelong North  victoria         Geelong

我希望得到不同的城市,区域1和区域2,因为不同的邮政编码可能存在重复。这是当前的查询。但我也想获取ID,因为这是我将把所选记录作为参考放入数据库中。

结果通缉:

我希望能够获得独特的'city,region1,region2

 geelong geelong victoria
 geelong geelong north victoria

初始查询获得这些结果

但我也想知道已经返回的记录的ID。我将在用户配置文件中使用此ID(存储在DB中)。例如:

 1 geelong geelong victoria
 3 geelong geelong north victoria

希望这能更好地解释它。 只需要包含返回的Distinct记录ID。

3 个答案:

答案 0 :(得分:0)

我没有检查过这个,但不会这样做:

SELECT DISTINCT (city,region1,region2), ID from static_geo_world where country='AU' AND
 (city LIKE '%geel%' OR region1 LIKE '%geel%' OR region2 LIKE '%geel%' OR region3 LIKE '%geel%' OR zip LIKE 'geel%') ORDER BY city;

希望这有效!

答案 1 :(得分:0)

你不能做你似乎要求的事情:

输入数据:

ID  City   Region1  Region2
--- ------ -------- --------
 1  geel1  geel2    geel3
 2  geel1  geel2    geel3
 3  geel4  geel5    geel6
 4  geel1  geel2    geel3

查询select distinct city,region1,region2返回

City   Region1  Region2
------ -------- --------
geel1  geel2    geel3
geel4  geel5    geel6 

删除重复的行后,不再有行的唯一ID。你说

  

如何获得与上述相同的UNIQUE记录集,同时获取每条记录的“id”

但是对于第一个返回的行,有三个可能的ID,并且为每个记录请求“id”是没有意义的。

修改

如果你只想要最低的ID,你可以这样做:

select min(id),city,region1,region2 from ... where ... group by city,region1,region2

答案 2 :(得分:-1)

改为使用group

SELECT id , city,region1,region2 from static_geo_world where country='AU' AND
(city LIKE '%geel%' OR region1 LIKE '%geel%' OR region2 LIKE '%geel%' OR region3 LIKE     '%geel%' OR zip LIKE 'geel%') ORDER BY city group by city;

这将返回您所需要的。但是从db记录中它总是会选择找到的第一条记录,如果city ='A',并且这个城市有很多记录,它将选择找到的第一条记录,并将返回其id