简体   繁体   English

需要对具有同一表上的多个联接的SQL查询执行数学运算

[英]Need to perform mathematical operation on SQL query with multiple joins on same table

I'm using WordPress for custom fields, and it basically has a meta_key column and a meta_value column in wp_postmeta table which I am using to store meta_keys 'longitude' and 'latitude' with meta_values say, 24.3 and 76.2 for one post_id of type 'gym'. 我使用WordPress的自定义字段,它基本上有一个meta_key列和meta_valuewp_postmeta表,我使用的存储meta_keys “经度”和“纬度”与meta_values一个说,24.3和76.2 post_id型“健身房'。

Now I need to query the database from Php to find the nearby gyms from the user position within a 10km radius. 现在,我需要从Php中查询数据库,以从半径10公里以内的用户位置查找附近的体育馆。 I am using the following query: 我正在使用以下查询:

                 SELECT
                 pm1.meta_value AS longitude,
                 pm2.meta_value AS latitude,
                 ACOS( SIN( RADIANS( pm2.meta_value ) ) * SIN( RADIANS( $user_lat ) ) + COS( RADIANS( pm2.meta_value ) )
                * COS( RADIANS( $user_lat )) * COS( RADIANS( pm1.meta_value ) - RADIANS( $user_lng )) ) * $earth_radius AS distance 

                 FROM `wp_postmeta` pm1
                   INNER JOIN `wp_postmeta` pm2 ON pm1.post_id = pm2.post_id

                 WHERE
                   pm1.meta_key = 'longitude'
                   AND pm2.meta_key = 'latitude'
                   AND ACOS( SIN( RADIANS( pm2.meta_value ) ) * SIN( RADIANS( $user_lat ) ) + COS( RADIANS( pm2.meta_value ) )
                * COS( RADIANS( $user_lat )) * COS( RADIANS( pm1.meta_value ) - RADIANS( $user_lng )) ) * $earth_radius < 10

where $user_lat and $user_lng are Php variables denoting user position. 其中$user_lat$user_lng是表示用户位置的Php变量。 This isn't working. 这不起作用。 The syntax seems to be correct but the calculated distances not. 语法似乎正确,但计算出的距离却不正确。 I got the inspiration for the query from radius search with google maps and mysql 我从谷歌地图和mysql的半径搜索中获得了查询的灵感

What am I doing wrong? 我究竟做错了什么?

UPDATE: The above code works. 更新:上面的代码有效。 I was making a very silly mistake. 我犯了一个非常愚蠢的错误。 Above code is a great resource for people facing the same problem where longitude and latitude fields aren't clearly defined, for example in the default WordPress custom fields table layout. 上面的代码对于面临相同问题的人们来说是一个很好的资源,在这些问题中, longitudelatitude字段没有明确定义,例如在默认的WordPress自定义字段表布局中。

Can't you just calculate distance between each gym and user position, and return the ones where distance <=10km? 您不能只计算每个健身房与用户位置之间的距离,然后返回距离<= 10km的距离吗?

For example: 例如:

User coordinates = (7, 2) 用户坐标=(7,2)

Gym1 coordinates = (2,4) Gym1坐标=(2,4)
Gym2 coordinates = (10,3) Gym2坐标=(10,3)
... ...

distance1 = sqrt((7-2)^2+(2-4)^2) 距离1 = sqrt((7-2)^ 2 +(2-4)^ 2)
distance2 = sqrt((7-10)^2+(2-3)^2) 距离2 = sqrt((7-10)^ 2 +(2-3)^ 2)
... ...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM