【发布时间】:2014-09-14 12:05:20
【问题描述】:
我正在尝试获取一个 SQL 查询来动态地提取城市范围内的事件。我有一个城镇/城市列表,通过谷歌地理编码,我可以获得每个城市的东北和西南边界。
我看到了解释如何检查某个位置(按纬度和经度)是否在美国等地范围内的代码,但我了解到这不适用于整个世界。
我试过下面的公式,但它似乎不起作用:
AND (
($swLat < $neLat AND lat BETWEEN $swLat AND $neLat)
OR
($neLat < $swLat AND lat BETWEEN $neLat AND $swLat)
AND
($swLng < $neLng AND lng BETWEEN $swLng AND $neLng)
OR
($neLng < $swLng AND lng BETWEEN $neLng AND $swLng)
)
刚刚尝试了下面的第一个建议,这是我得到的输出:
SELECT SQL_CALC_FOUND_ROWS wp_posts.ID
FROM wp_posts
INNER JOIN lat_lng_post ON wp_posts.ID = lat_lng_post.post_id
WHERE 1=1
AND wp_posts.ID IN (10027,10095,...,10657)
AND wp_posts.post_type = 'event'
AND (wp_posts.post_status = 'publish' OR wp_posts.post_status = 'private')
AND lat_lng_post.lat = lat
AND lat_lng_post.lng = lng
AND (
(
(52.385999 < 52.5688762) AND (lat BETWEEN 52.385999 AND 52.5688762)
OR
(52.5688762 < 52.385999) AND (lat BETWEEN 52.5688762 AND 52.385999)
) AND (
(-2.0174336 < -1.7098294) AND (lng BETWEEN -2.0174336 AND -1.7098294)
OR
(-1.7098294 < -2.0174336) AND (lng BETWEEN -1.7098294 AND -2.0174336)
)
)
ORDER BY wp_posts.post_date DESC
LIMIT 0, 10
编辑 2 根据 barryhunter 的回答,我有这个在查询中调用的函数:
function bounds_query($bounds) {
$swLat = $_SESSION['search']['SW'][0];
$swLng = $_SESSION['search']['SW'][1];
$neLat = $_SESSION['search']['NE'][0];
$neLng = $_SESSION['search']['NE'][1];
$bounds .= ' AND (lat BETWEEN '.$swLat.' AND '.$neLat.')';
if ($neLng < $swLng) {
$bounds .= ' AND NOT (lng BETWEEN '.$neLng.' AND '.$swLng.')';
} else {
$bounds .= ' AND (lng BETWEEN '.$swLng.' AND '.$neLng.')';
}
return $bounds;
}
这会输出以下 SQL:
SELECT SQL_CALC_FOUND_ROWS wp_posts.ID
FROM wp_posts
INNER JOIN lat_lng_post
ON wp_posts.ID = lat_lng_post.post_id
WHERE 1=1
AND wp_posts.ID IN (10060,10293,...,10657)
AND wp_posts.post_type = 'event'
AND (wp_posts.post_status = 'publish' OR wp_posts.post_status = 'private')
AND lat_lng_post.lat = lat
AND lat_lng_post.lng = lng
AND (lat BETWEEN 52.385999 AND 52.5688762) AND (lng BETWEEN -2.0174336 AND -1.7098294)
ORDER BY wp_posts.post_date DESC
LIMIT 0, 10
【问题讨论】:
标签: mysql sql geolocation