如何在MySQL中仅为一列应用DISTINCT选择器

时间:2012-09-07 12:40:38

标签: mysql sql

我有一张如下表: -

Table: deals
+----+-------+----------+----------+------------+
| ID |  name | latitude | longitude|  end_date  |
|----+-------+----------+----------+------------+
|  1 | pizza |    10.5  |   -10.5  | 2012-12-12 |
|  2 | pizza |    11.5  |   -10.5  | 2012-12-12 |
|  3 | jelly |    21.5  |   -10.5  | 2012-12-12 |
|  4 | jelly |    23.5  |   -10.5  | 2012-12-12 |
|  5 | lily  |    19.5  |   -10.5  | 2012-12-12 |
+----+-------+----------+----------+------------+

我正在使用latitudelongitude来查找与该人的距离。但我需要基于DISTINCT的结果name。我还需要按照我计算的距离对结果进行排序,并应用限制0,3。

我目前使用的查询是“ -

SELECT *,
   ( 6371 * Acos(Cos(Radians(9.939625)) * Cos(Radians(lat)) * Cos(
                               Radians(lng) - Radians(76.259498)) +
                          Sin(Radians(9.939625)) * Sin(Radians(lat))) ) AS
   distance
FROM   deals
WHERE  1
   AND end_date >= Now()
HAVING distance < 20000
ORDER  BY id DESC,
      distance
LIMIT  0, 3;  

简而言之,我需要的是: -

  1. 最近的交易列表(按距离排序)
  2. 将{distinct>应用于name(这样披萨和果冻只会出现一次)

2 个答案:

答案 0 :(得分:2)

您需要应用MIN来获取每个名称的最小距离,GROUP BY名称(每个名称产生一个结果)和ORDER BY距离优先,以及稍后的ID;

SELECT *,
   MIN( 6371 * Acos(Cos(Radians(9.939625)) * Cos(Radians(latitude)) * Cos(
                               Radians(longitude) - Radians(76.259498)) +
                          Sin(Radians(9.939625)) * Sin(Radians(latitude))) ) 
AS distance
FROM   deals
WHERE  end_date >= Now()
GROUP BY name
ORDER  BY distance, id DESC

我应该补充一点,这个查询可能适用于您的情况,但通常不是非常有用,因为如果您想知道最近的披萨店的纬度和经度,您将需要一个完全不同的查询。

答案 1 :(得分:0)

SELECT *, 
   ( 6371 * Acos(Cos(Radians(9.939625)) * Cos(Radians(lat)) * Cos( 
                               Radians(lng) - Radians(76.259498)) + 
                          Sin(Radians(9.939625)) * Sin(Radians(lat))) ) AS 
   distance 
FROM   deals 
WHERE  1 
   AND end_date >= Now() 
GROUP BY name
HAVING distance < 20000 
ORDER  BY id DESC, 
      distance