Mysql组按冲突记录顺序排列

时间:2016-07-15 13:56:19

标签: mysql group-by sql-order-by

一张桌子包含经销商的多个地址(纬度和经度),但我想找到最近的经销商

以下是查询哪个退货可以正常运行,经销商= 1个单一经销商,但我需要多个独特的经销商。

检查查询和第一张图片结果

SELECT 

  *, ROUND(
    (
      3959 * ACOS(
        COS(RADIANS(41.355724)) * COS(
          RADIANS(adzip.dealer_zipcode_latitude)
        ) * COS(
          RADIANS(adzip.dealer_zipcode_longitude) - RADIANS(- 87.607332)
        ) + SIN(RADIANS(41.355724)) * SIN(
          RADIANS(adzip.dealer_zipcode_latitude)
        )
      )
    ), 2
  ) AS dealer_distance 
FROM
  ad_dealers_zipcodes AS adzip 
WHERE adzip.dealer_zipcode_dealer_id = 1 #GROUP BY adzip.dealer_zipcode_dealer_id
ORDER BY dealer_distance ASC 

enter awfawefawefa description here 当我通过adzip.dealer_zipcode_dealer_id添加分组查询返回第4条记录但是我需要第1条结果记录,其中dealer_distance是13.80

enter image description here

1 个答案:

答案 0 :(得分:2)

实际上,我认为您应该在查询中为group by语句添加一个级别,以便按照您的意图工作,如下所示:

SELECT *, min(dealer_distance) AS min_dealer_distance  FROM 
(
    SELECT 

      *, ROUND(
        (
          3959 * ACOS(
            COS(RADIANS(41.355724)) * COS(
              RADIANS(adzip.dealer_zipcode_latitude)
            ) * COS(
              RADIANS(adzip.dealer_zipcode_longitude) - RADIANS(- 87.607332)
            ) + SIN(RADIANS(41.355724)) * SIN(
              RADIANS(adzip.dealer_zipcode_latitude)
            )
          )
        ), 2
      ) AS dealer_distance 
    FROM
      ad_dealers_zipcodes AS adzip 
    WHERE adzip.dealer_zipcode_dealer_id = 1 #GROUP BY adzip.dealer_zipcode_dealer_id
    ORDER BY dealer_distance ASC 
) as t1
GROUP BY dealer_zipcode_dealer_id
ORDER BY min_dealer_distance ASC