2

我有一张如下表:-

表:交易
+----+--------+---------+----------+------------+
| 身份证 | 姓名 | 纬度 | 经度| 结束日期 |
|----+--------+----------+----------+------------+
| 1 | 比萨饼| 10.5 | -10.5 | 2012-12-12 |
| 2 | 比萨饼| 11.5 | -10.5 | 2012-12-12 |
| 3 | 果冻| 21.5 | -10.5 | 2012-12-12 |
| 4 | 果冻| 23.5 | -10.5 | 2012-12-12 |
| 5 | 百合 | 19.5 | -10.5 | 2012-12-12 |
+----+--------+---------+----------+------------+

我正在使用latitudeandlongitude来查找到那个人的距离。但我需要结果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 to name(这样比萨饼和果冻都只会出现一次)
4

2 回答 2

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

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

于 2012-09-07T12:49:10.993 回答
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 
于 2012-09-07T12:46:20.853 回答