2011-07-06 71 views
3

我試圖創建使用ActiveRecord用笨的活動記錄爲「距離之內」查詢

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 

在CI下面的查詢我試圖

$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()功能。距離查詢應與其他條款共存。

回答

4

您正在將SQL中的distance計算設置爲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); 
+0

謝謝!它現在的作品:) – CyberJunkie

-1

$ miles = 20; (cos(弧度($ shop_lat))* cos(弧度(lat))* cos(弧度(lng) - 弧度($ shop_long))+ sin (弧度($ shop_lat))* sin(弧度(lat))))AS距離「);
$ this-> db-> from('shop'); $ this-> db-> having('distance < ='。$ miles);
$ this-> db-> order_by('distance');
$ this-> db-> limit(20,0); $ query = $ this-> db-> get(); $ result = $ query-> result(); 返回$結果; }

+0

澄清你的答案,但也要記住,這是關閉了5年前。 – Takarii