我正在尝试使用Haversine公式从WordPress数据库中获取最近的地点
我的表结构如下
posts
+--------------+ | Field | +--------------+ | ID | | post_author | | post_title | | post_type | +--------------+
postmeta
+--------------+ | Field | +--------------+ | meta_id | | post_id | | meta_key | | meta_value | +--------------+
并有记录与meta_key值latitude和longitude
meta_key
latitude
longitude
SELECT p.ID, p.post_title, p.post_author, max(case when pm.meta_key='latitude' then pm.meta_value end) latitude, max(case when pm.meta_key='longitude' then pm.meta_value end) longitude FROM `wp_posts` p LEFT JOIN `wp_postmeta` pm on p.ID=pm.post_id WHERE p.post_type='place' AND (pm.meta_key='latitude' OR pm.meta_key='longitude') GROUP BY p.ID, p.post_title, p.post_author ORDER BY p.ID ASC
现在我想将以上查询合并到该问题的答案中
SELECT item1, item2, ( 3959 * acos( cos( radians(37) ) * cos( radians( lat ) ) * cos( radians( lng ) - radians(-122) ) + sin( radians(37) ) * sin( radians( lat ) ) ) ) AS distance FROM geocodeTable HAVING distance < 25 ORDER BY distance LIMIT 0 , 20;
以下是通过组合查询
SELECT ID, post_title, post_author, max(case when meta_key='latitude' then meta_value end) latitude, max(case when meta_key='longitude' then meta_value end) longitude, ( 3959 * acos( cos( radians(18.204540500000) ) * cos( radians( latitude ) ) * cos( radians( longitude ) - radians(-66.450958500000) ) + sin( radians(18.204540500000 ) * sin( radians( latitude ) ) ) ) AS distance FROM `wp_posts` LEFT JOIN `wp_postmeta` on ID=post_id WHERE post_type='place' AND (meta_key='latitude' OR meta_key='longitude') GROUP BY ID, post_title, post_author ORDER BY ID ASC
但这会产生语法错误
#1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'AS distance FROM `wp_posts` LEFT JOIN `wp_postmeta` on ID=post_id WHERE po' at line 13
您错过了)第一个闭幕式sin()
)
sin()
( 3959 * acos( cos( radians(18.204540500000) ) * cos( radians( latitude ) ) * cos( radians( longitude ) - radians(-66.450958500000) ) + sin( radians(18.204540500000 ) ) /* <--- here */ * sin( radians( latitude ) ) ) ) AS distance
尽管很难从视觉上发现它,但我通过将您的代码复制到支持大括号匹配的文本编辑器中发现了这一点。强烈建议使用一种,如果不是用于查询开发和测试,则至少要用于调试。