删除具有相同列值的行

时间:2011-04-08 05:28:18

标签: php mysql unique distinct

我正在从邮政编码表中查询一堆城市。我只想用一个独特的“城市”来获取结果。 (很多城市有多个拉链。)怎么可能这样做?

    $query = sprintf("SELECT `Zip`, `City`, `State`, `Lat`, `Long`, 
             ( 3959 * acos( cos( radians('%s') ) * cos( radians( `Lat` ) ) * 
             cos( radians( `Long` ) - radians('%s') ) +
             sin( radians('%s') ) * sin( radians( `Lat` ) ) ) ) AS distance 
             FROM Zips HAVING distance < '%s' ORDER BY distance LIMIT 0 , 18",
      mysql_real_escape_string($lat),
      mysql_real_escape_string($lng),
      mysql_real_escape_string($lat),
      mysql_real_escape_string($radius));
    $result = mysql_query($query, $dbConn);

2 个答案:

答案 0 :(得分:1)

您在错误的地方使用HAVING此处需要WHERE,并使用GROUP BY按城市分组结果

 $query = sprintf("SELECT `Zip`, `City`, `State`, `Lat`, `Long`, ( 3959 * acos( cos(
 radians('%s') ) * cos( radians( `Lat` ) ) * cos( radians( `Long` ) - radians('%s') ) + sin(
 radians('%s') ) * sin( radians( `Lat` ) ) ) ) AS distance FROM Zips WHERE distance < '%s'  
 GROUP BY City ORDER BY distance LIMIT 0 , 18",

修改

您也可以尝试

     $query = sprintf("SELECT `Zip`, `City`, `State`, `Lat`, `Long`, ( 3959 * acos( cos(
     radians('%s') ) * cos( radians( `Lat` ) ) * cos( radians( `Long` ) - radians('%s') ) + sin(
     radians('%s') ) * sin( radians( `Lat` ) ) ) ) AS distance FROM Zips HAVING distance < '%s'  
     GROUP BY City  ORDER BY distance LIMIT 0 , 18";

OR

$query = sprintf("SELECT * FROM (SELECT `Zip`, `City`, `State`, `Lat`, `Long`, ( 3959 * acos( cos(
     radians('%s') ) * cos( radians( `Lat` ) ) * cos( radians( `Long` ) - radians('%s') ) + sin(
     radians('%s') ) * sin( radians( `Lat` ) ) ) ) AS distance FROM Zips HAVING distance < '%s'  
     ORDER BY distance LIMIT 0 , 18 ) as result_set GROUP BY City";

答案 1 :(得分:0)

尝试

SELECT DISTINCT(city)

OR

GROUP BY (City)