php-使用Codeigniter活动记录进行“距离内”查询

我正在尝试使用ActiveRecord在CI中创建以下查询

SELECT *, 
   ( 3959 * acos( cos( radians($lat) ) 
   * cos( radians( lat ) ) 
   * cos( radians( lng ) - radians($lng) ) 
   + sin( radians($lat) ) 
   * sin( radians( lat ) ) ) ) AS distance 
FROM locations 
HAVING distance <= $miles 
ORDER BY distance 
LIMIT 0, 20

我试过了

$where = "( 3959 * acos( cos( radians($lat) ) * cos( radians( lat ) ) * cos( radians( lng ) - radians($lng) ) + sin( radians($lat) ) * sin( radians( lat ) ) ) ) AS distance FROM locations";        
$this->db->where($where);                           
$this->db->having('distance <= ' . $miles);                     
$this->db->order_by('distance');                    
$this->db->limit(20, 0);

问题(我认为)是我已经在告诉我我是通过$query = $this-> db-> get(‘locations’);从哪个表获取数据的.在我模型的结尾所以我收到以下错误:

A Database Error Occurred Error
Number: 1064

You have an error in your SQL syntax;
check the manual that corresponds to
your MySQL server version for the
right syntax to use near ‘AS distance
FROM user_profiles HAVING distance
<= 100 ORDER BY distance LIMI’ at
line 5

SELECT * FROM (locations) WHERE
country = ‘US’ AND tags = ‘technology’ AND
( 3959 * acos( cos(
radians(25.9331488) ) * cos( radians(
lat ) ) * cos( radians( lng ) -
radians(-80.1625463) ) + sin(
radians(25.9331488) ) * sin( radians(
lat ) ) ) ) AS distance FROM
locations HAVING
distance<= 100
ORDER BY
distance` LIMIT 20

Filename:
C:\wamp\www\mysite\system\database\DB_driver.php

Line Number: 330

一些注意事项..我在模型中使用了几个where()函数.距离查询应与其他子句共存.

解决方法:

您正在SQL中将距离计算设置为WHERE.您需要在SELECT中选择它.没有测试,但是尝试:

$this->db->select("*, ( 3959 * acos( cos( radians($lat) ) * cos( radians( lat ) ) * cos( radians( lng ) - radians($lng) ) + sin( radians($lat) ) * sin( radians( lat ) ) ) ) AS distance");                         
$this->db->having('distance <= ' . $miles);                     
$this->db->order_by('distance');                    
$this->db->limit(20, 0);
上一篇:php-代码点火器和配置文件中的自定义库?


下一篇:PHP-如何使用Codeigniter显示我的表格字段中计数的结果