我在数据库中有一张位置表。我需要查询以找到最近的位置(提供任何坐标)。我编写了以下查询,以获取所有行以及它们与给定坐标的距离(以米为单位的距离):
SELECT *, 111111 * DEGREES(ACOS(LEAST(COS(RADIANS(dest.latitude)) * COS(RADIANS(8.584710)) * COS(RADIANS(dest.longitude - 76.868735)) + SIN(RADIANS(dest.latitude)) * SIN(RADIANS(8.584710)), 1.0))) as distance FROM offer dest;
它提供以下输出:
+----+------------------------+----------+-----------+------------+---------------------+
| id | description | latitude | longitude | name | distance |
+----+------------------------+----------+-----------+------------+---------------------+
| 2 | Location 1 Description | 8.574858 | 76.874748 | Location 1 | 1278.565430298969 |
| 12 | Location 2 Description | 8.584711 | 76.868738 | Location 2 | 0.35494725284463646 |
+----+------------------------+----------+-----------+------------+---------------------+
一切正常。现在,要获取最小距离,我在此查询中添加了HAVING MIN(distance)
。现在查询如下所示:
SELECT *, 111111 * DEGREES(ACOS(LEAST(COS(RADIANS(dest.latitude)) * COS(RADIANS(8.584710)) * COS(RADIANS(dest.longitude - 76.868735)) + SIN(RADIANS(dest.latitude)) * SIN(RADIANS(8.584710)), 1.0))) as distance FROM offer dest having MIN(distance);
现在,此查询应该返回1行,应该是位置2,因为它具有最小的位置,但是返回的是位置1,如下所示:
+----+------------------------+----------+-----------+------------+---------------------+
| id | description | latitude | longitude | name | distance |
+----+------------------------+----------+-----------+------------+---------------------+
| 2 | Location 1 Description | 8.574858 | 76.874748 | Location 1 | 1278.565430298969 |
+----+------------------------+----------+-----------+------------+---------------------+
为什么这样?我的查询有问题吗?如果是的话,那是什么?如何以最小的距离获得位置。
答案 0 :(得分:2)
HAVING
子句用于过滤组的条件。使用SELECT
部分的集合函数和GROUP BY
定义组。由于您都没有这些,因此不应该使用HAVING
。
如果要按行距离显示距行集的最小距离,并将结果集限制为仅一行。
SELECT *,
111111 * DEGREES(ACOS(LEAST(COS(RADIANS(dest.latitude)) *
COS(RADIANS(8.584710)) * COS(RADIANS(dest.longitude - 76.868735)) +
SIN(RADIANS(dest.latitude)) * SIN(RADIANS(8.584710)), 1.0))) as distance
FROM offer dest
ORDER BY distance
LIMIT 1;