简体   繁体   中英

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'.

Now I need to query the database from Php to find the nearby gyms from the user position within a 10km radius. 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. 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

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.

Can't you just calculate distance between each gym and user position, and return the ones where distance <=10km?

For example:

User coordinates = (7, 2)

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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