使用列值作为列名mysql [英] use column value as column name mysql
问题描述
我正在尝试使所有用户的半径都在5公里以内.这是我的表结构
I am trying to get all users in 5 KM radius. here is my table structure
id| location
-------------
1| 26.851791,75.781810
2| 26.860729,75.7633127
3| 34.057811,-84.239125
我写了一个查询以根据lat
和long
I write a query to separate the location according to lat
and long
SELECT SUBSTRING_INDEX( location, ',', 1 ) AS lat, SUBSTRING_INDEX( location, ',', -1 ) AS lng
FROM `users_test`
LIMIT 0 , 30
哪个工作正常,我得到的结果如下?
Which work fine and I got results as following
然后,根据以下博客,我编写一个查询以获取所有位于5KM Radius中的用户.
then I write a query to get all the users who are in 5KM Radius according to the following blog.
https://www.marketingtechblog.com/calculate-distance/ >
SELECT *,SUBSTRING_INDEX( location, ',', 1 ) AS lat, SUBSTRING_INDEX( location, ',', -1 ) AS lng,(((acos(sin(("26.851791"*pi()/180)) * sin((`lat`*pi()/180))+cos(("26.851791"*pi()/180)) * cos((`lat`*pi()/180)) * cos((("75.781810"- `lng`)*pi()/180))))*180/pi())*60*1.1515*1.609344) as distance
FROM `users_test`
WHERE distance >= "5"
但是我遇到以下错误.
#1054-字段列表"中的未知列"lat"
#1054 - Unknown column 'lat' in 'field list'
谁能告诉我我哪里错了.
can anyone tell me where I am wrong.
推荐答案
您不能在同一SELECT
子句中引用列别名.您需要将其移动到子查询中.而且您不能在同一SELECT
的WHERE
子句中引用别名,您需要使用HAVING
.
You can't refer to a column alias in the same SELECT
clause. You need to move it into a subquery. And you can't refer to an alias in the WHERE
clause of the same SELECT
, you need to use HAVING
.
SELECT *, (((acos(sin(("26.851791"*pi()/180)) * sin((`lat`*pi()/180))+cos(("26.851791"*pi()/180)) * cos((`lat`*pi()/180)) * cos((("75.781810"- `lng`)*pi()/180))))*180/pi())*60*1.1515*1.609344) as distance
FROM (SELECT *,
SUBSTRING_INDEX( location, ',', 1 ) AS lat,
SUBSTRING_INDEX( location, ',', -1 ) AS lng
FROM users_test) x
HAVING distance > 5
我强烈建议您修正表格设计,将纬度和经度放在自己的列中,而不必每次都用逗号分开.
I strongly suggest you fix your table design to put the latitude and longitude in their own columns, instead of having to split on comma every time.
这篇关于使用列值作为列名mysql的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!