我试图在PHP + MySQL中构建基于位置的事件搜索(使用Laravel及其Eloquent ORM)
这是我正在使用的查询:
select
events.*,
( 3959 * acos( cos( radians(50.5) ) * cos( radians( addresses.latitude ) ) * cos( radians( addresses.longitude ) - radians(9.50) ) + sin( radians(50.5) ) * sin( radians( addresses.latitude ) ) ) ) AS distance
from
`events` inner join `addresses` on `events`.`address_id` = `addresses`.`id`
having
`distance` <= 10
order by
`id` desc limit 15 offset 0
我想知道为什么会弹出这个错误,即使距离列在“选择语句”中。
"SQLSTATE[42S22]: Column not found: 1054 Unknown column 'distance' in 'having clause' (SQL: select count(*) as aggregate from `events` inner join `addresses` on `events`.`address_id` = `addresses`.`id` having `distance` <= 10 order by `id` desc)"
这是我用来将范围添加到基本查询的PHP代码:
$selectDistance =
'( 3959 * acos( cos( radians(' . $latitude . ') ) ' .
'* cos( radians( addresses.latitude ) ) ' .
'* cos( radians( addresses.longitude ) - radians(' . $longitude . ') ) ' .
'+ sin( radians(' . $latitude . ') ) ' .
'* sin( radians( addresses.latitude ) ) ) ) AS distance';
$query->select(DB::raw('events.*, ' . $selectDistance));
$query->join('addresses', 'events.address_id', '=', 'addresses.id');
$query->having('distance', '<=', $km);
非常感谢:)
答案 0 :(得分:3)
从错误消息:
&#34; SQLSTATE [42S22]:未找到列:1054未知列&#39;距离&#39;在 &#39;有条款&#39; (SQL:从
events
内部选择count(*)作为聚合 在addresses
上加入events
。address_id
=addresses
。id
distance
&lt; = 10订单id
desc)&#34;
我们可以得到以下
select count(*) as aggregate
from `events` inner join `addresses` on `events`.`address_id` = `addresses`.`id`
having `distance` <= 10
order by `id` desc
distance
不在选择列表中。
答案 1 :(得分:1)
HAVING子句是在SQL中引入的,因为我们不能将聚合函数与WHERE关键字一起使用。根据您的查询,SELECT语句或HAVING子句中没有聚合函数。因此,请尝试更改
having
`distance` <= 10
到
where
`distance` <= 10
HAVING子句应以下列格式使用。
HAVING aggregate_function(column_name) operator value
运算符 可以是=,&gt;,&lt; ,&lt; =,等等....
此外,您的PHP代码也需要相应更改。
下面的SQL教程链接可以帮助您更好地理解SQL中HAVING子句的使用。
答案 2 :(得分:0)
您可以尝试类似的事情
$selectDistance =
'( 3959 * acos( cos( radians(' . $latitude . ') ) ' .
'* cos( radians( addresses.latitude ) ) ' .
'* cos( radians( addresses.longitude ) - radians(' . $longitude . ') ) ' .
'+ sin( radians(' . $latitude . ') ) ' .
'* sin( radians( addresses.latitude ) ) ) )';
$query->join('addresses', 'events.address_id', '=', 'addresses.id')
->select(DB::raw('events.*))
->selectRaw("{$selectDistance} AS distance")
->whereRaw("{$selectDistance} < ?", 10)
->get();