我无法解决这个问题:
我有许多地理坐标的mysql DB。
我想知道哪些点在距离特定坐标的特定英里数内,并且哪些在特定正方形内。
特定区域内的点:
(SELECT
*,
'area' as type,
( 3959 * acos( cos( radians(".$Plat.") ) * cos( radians( lat ) ) * cos( radians( lng ) - radians(".$Plng.") ) + sin( radians(".$lat.") ) * sin( radians( lat ) ) ) ) AS distance
FROM
".$db."
HAVING
distance < ".$radius."
特定方块内的点:
SELECT
*,
'square' as type,
-1 AS distance
FROM
".$db."
WHERE
((Alat <= ".$Alat." AND ".$Alat." <= Blat) OR (Alat >= ".$Alat." AND ".$Alat." >= Blat)) AND
((Alng <= ".$Alng." AND ".$Alng." <= Blng) OR (Alng >= ".$Alng." AND ".$Alng." >= Blng))
...
我使用 UNION 组合这两个查询,但问题是"类型"和"距离"具有不同的值。所以我得到了两次搜索点。我喜欢每一点都只有一次。
但我不知道如何处理这个问题。
编辑:
为了概述,我只获取了一些数据。
结果我得到这样的东西:
+------+-----------+-----------+----------+-------------+
| id | Alat | Alng | distance | type |
+------+-----------+-----------+----------+-------------+
| 42 | 53.704678 | 10.202164 | 12345 | area
+------+-----------+-----------+------------------------+
| 72 | 23.704678 | 15.202164 | 12345 | area
+------+-----------+-----------+------------------------+
......
+------+-----------+-----------+------------------------+
| 42 | 53.704678 | 10.202164 | -1 | square
+------+-----------+-----------+------------------------+
| 81 | 43.778 | 15.201212 | -1 | square
+------+-----------+-----------+------------------------+
......
- id(72) 只存在于正方形中。
- id(81) 只存在于正方形中,而不是在该区域中。
- id(42) 在该地区,也在广场上。所以它出现了两次。但它只应该只有一次。该地区应获得优先权。
但它应该是
+------+-----------+-----------+----------+-------------+
| id | Alat | Alng | distance | type |
+------+-----------+-----------+----------+-------------+
| 42 | 53.704678 | 10.202164 | 12345 | area
+------+-----------+-----------+------------------------+
| 72 | 23.704678 | 15.202164 | 12345 | area
+------+-----------+-----------+------------------------+
......
+------+-----------+-----------+------------------------+
| 81 | 43.778 | 15.201212 | -1 | square
+------+-----------+-----------+------------------------+
......
在 UNION 之后使用 GROUP BY 删除重复项。
SELECT id, Alat, Alng, distance, type
FROM (
SELECT *, 'area' as type, ... FROM ...
UNION ALL
SELECT *, 'square' as type, ... FROM ...
) AS subq
GROUP BY id, Alat, Alng, distance
对于较大的结果集,这可能不是很有效,但应该可以工作。
请注意,这种GROUP BY在SQL标准和许多其他数据库中是被禁止的(因为type
不在GROUP BY中),但MySQL允许这样做。