SQL 请求,用 MySQL 找到离我最近的人

SQL request, find people closest to me with MySQL

我目前正在做一个 Wordpress/PHP/MySQL 项目。

我想运行查询以查找地理位置靠近登录用户的人。

为此,我在 usermeta table 中为用户设置了两个自定义字段,纬度和经度如下所示:

我想生成一个 SQL 查询,其中“45.7699”是用户的纬度,“4.8037”是他们的经度:

SELECT lat AS lat, lng AS lng, (6366*acos(cos(radians(45.7699))*cos(radians(lat))*cos(radians(lng) -radians(4.8037))+sin(radians(45.7699))*sin(radians(lat)))) AS dist FROM air_usermeta WHERE (6366*acos(cos(radians(45.7699))*cos(radians(lat))*cos(radians(lng) -radians(4.8037))+sin(radians(45.7699))*sin(radians(lat))))<='50' ORDER by dist ASC

我的问题在开头:

SELECT lat AS lat, lng AS lng

如何在 lat 和 lng 字段不是列而是 meta_value 的 Wordpress 上下文中检索值。

非常感谢您的帮助。

[已解决]

SELECT a.user_id, a.meta_value AS lat, b.meta_value AS lng FROM air_usermeta as a, air_usermeta as b WHERE a.meta_key = "lat" AND b.meta_key= "lng" AND a.user_id = b.user_id AND (6366*acos(cos(radians(45.7699))*cos(radians(a.meta_value))*cos(radians(b.meta_value) -radians(4.8037))+sin(radians(45.7699))*sin(radians(a.meta_value))))<='20' ORDER by (6366*acos(cos(radians(45.7699))*cos(radians(a.meta_value))*cos(radians(b.meta_value) -radians(4.8037))+sin(radians(45.7699))*sin(radians(a.meta_value)))) ASC

您可以select使用自连接

SELECT a.id, a.meta_value as lat, b.meta_value as lng
FROM lbt_postmeta as a, 
lbt_postmeta as b
WHERE a.meta_key = "lat"
AND b.meta_key= "lng"
AND a.id = b.id