我正在尝试使用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: 1064You 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 HAVINGdistance
<= 100 ORDER BYdistance
LIMI’ at
line 5SELECT * FROM (
locations
) WHEREcountry
= ‘US’ ANDtags
= ‘technology’ ANDdistance
( 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<= 100
distance` LIMIT 20
ORDER BYFilename:
C:\wamp\www\mysite\system\database\DB_driver.phpLine 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);