2015-05-29 59 views
1

此查询的工作:MySQL列没有被发现,尽管被宣布?

select d.*, 
(6371 * 3.1415926 * SQRT((:lat - dl.lat) * (:lat - dl.lat) + COS(:lat/57.2957795) * COS(dl.lat/57.2957795) * (:long - dl.long) * (:long - dl.long))/180) as xdistance 
from `dudes` as d 
left join `dude_locations` as dl on (dl.id_dude = d.id) 
where 
(6371 * 3.1415926 * SQRT((:lat - dl.lat) * (:lat - dl.lat) + COS(:lat/57.2957795) * COS(dl.lat/57.2957795) * (:long - dl.long) * (:long - dl.long))/180) <= dl.distance 
group by d.id 
limit 20 

然而,这个查询抛出一个“列xdistance未找到”错误:

select d.*, 
(6371 * 3.1415926 * SQRT((:lat - dl.lat) * (:lat - dl.lat) + COS(:lat/57.2957795) * COS(dl.lat/57.2957795) * (:long - dl.long) * (:long - dl.long))/180) as xdistance 
from `dudes` as d 
left join `dude_locations` as dl on (dl.id_dude = d.id) 
where 
xdistance <= dl.distance 
group by d.id 
limit 20 

所有我想要做的就是它,因此同样的计算ISN”做了两次。这可能吗?

任何帮助,将不胜感激。

+0

您的查询需要一些改进。您正在使用'left join',然后第二个表上的条件将它变成一个'inner join'。你在'select'中有距离计算,但是'group by'不包含这些变量 - 所以你会得到一个不确定的结果。 –

+0

工作查询为我提供了我想要的确切结果。你会如何写它?你可能会创建一个答案,你将如何编写查询?我不是想让你为我做我的工作,我只是好奇。 – inkd

+1

。 。它可能会给你你想要的结果*现在*。但是,当您使用明确记录不起作用的功能时(https://dev.mysql.com/doc/refman/5.6/en/group-by-handling.html),那么您将冒着代码失败的风险随时工作。我认为你可以通过将'distance'计算放在像'min()'这样的运算符中来修复查询。 –

回答

1
where 
d.xdistance <= dl.distance 
+0

不起作用。我现在得到'未知列d.distance'。 – inkd

+0

@inkd我认为错误会是未知列d.xdistance – wiretext

+0

是的,我犯了一个错字。 – inkd

1

这可能是你想要的查询是这样的:

select d.*, 
     MIN((6371 * 3.1415926 * SQRT((:lat - dl.lat) * (:lat - dl.lat) + COS(:lat/57.2957795) * COS(dl.lat/57.2957795) * (:long - dl.long) * (:long - dl.long))/180)) as xdistance 
from `dudes` as d left join 
    `dude_locations` as dl 
    on (dl.id_dude = d.id) 
group by d.id 
having xdistance <= min(dl.distance) 
limit 20;