我的数据库中有一个位于16英里处的Block Realty记录。
SELECT x.companyname, x.distance, y.city, y.zip
FROM (SELECT userid, companyname, lat, lng,
(3959 * acos(cos(radians(42.323617)) *
cos(radians(lat)) * cos(radians(lng) - radians(-83.200811)) +
sin(radians(42.323617)) * sin(radians(lat)))) AS distance
FROM users
WHERE (usertype = 2 OR usertype = 3)
HAVING distance < 25
order by distance) x
INNER JOIN
(select * from users where find_in_set('Real Estate',profession) <> 0) y
ON x.userid = y.userid
当我更新下面的查询以添加城市或邮编条件并减少距离搜索范围时,我收到错误#1054 - 未知列&#39;城市&#39;在&#39;有条款&#39; 。我该如何纠正?
SELECT x.companyname, x.distance, y.city, y.zip
FROM (SELECT userid, companyname, lat, lng,
(3959 * acos(...) AS distance
FROM users
WHERE (usertype = 2 OR usertype = 3)
HAVING distance < 11
AND (city = 'Detroit' OR zip = '48221')
order by distance) x
INNER JOIN
(select * from users where find_in_set('Real Estate',profession) <> 0) y
ON x.userid = y.userid
答案 0 :(得分:3)
将这些条件移至where
子句:
SELECT x.companyname, x.distance, y.city, y.zip
FROM (SELECT userid, companyname, lat, lng,
(3959 * acos(...) AS distance
FROM users
WHERE usertype IN (2, 3) AND
(city = 'Detroit' OR zip = '48221')
HAVING distance < 11
order by distance
) x INNER JOIN
(select * from users where find_in_set('Real Estate',profession) <> 0) y
ON x.userid = y.userid;
编辑:
原始版本无法正常工作的原因是having
子句需要引用select
中定义的列别名。所以,你也可以这样做:
SELECT x.companyname, x.distance, y.city, y.zip
FROM (SELECT userid, companyname, lat, lng, city, zip
(3959 * acos(...) AS distance
FROM users
WHERE usertype IN (2, 3)
HAVING distance < 11 OR (city = 'Detroit' OR zip = '48221')
order by distance
) x INNER JOIN
(select * from users where find_in_set('Real Estate',profession) <> 0) y
ON x.userid = y.userid;