My current code
SELECT post_id, ( 3959 * ACOS( COS( RADIANS( 34.09 ) ) * COS( RADIANS( lat ) ) * COS( RADIANS( lng ) - RADIANS( -117.55 ) ) + SIN( RADIANS( 34.09 ) ) * SIN( RADIANS( lat ) ) ) ) AS distance FROM wp_postmeta WHERE `meta_key` LIKE '%location_l%' HAVING distance < 2500 ORDER BY distance LIMIT 0 , 20
Here are two sample row of data (meta_key is not always long or lat):
post_id = 123
meta_key = location_longitude
meta_value = -119.890000
post_id = 123
meta_key = location_latitude
meta_value = 42.170000
How do I modify my query to replace ‘lat’ and ‘lng’ in my original query to be the contents of the meta_value listed above? Something like this?
select meta_value where meta_key = location_latitude
If you
GROUP BY post_id, you should be able to useMAX()aggregates in place oflat,lng, surroundingCASEstatements which determine whether the current row is latitude or longitude. The others will be NULL, and therefore eliminated by the aggregate.I think this ought to work so you won’t need any subselects.
The moving parts here are:
This translates as: If this row’s
meta_keyis'location_latitude', return themeta_value, otherwise return NULL. We expect then that since two rows are returned for thepost_id(lat,lng), theMAX()value returned above is always the non-null one — the correct latitude or longitude value frommeta_value.