2011-12-22 79 views
1

我有3個表用戶,配置文件和位置。這些表的結構是:複雜codeignitor用戶搜索查詢

user

user_id | email | pass | activated | banned 

profile

user_id | name | birthday | picture | gender | last_active 

location

user_id | city | country | latitude | longitude 

現在,這裏是搜索條件:

  1. 必須激活用戶(1)才能顯示在搜索結果中。
  2. 不能禁止用戶(0)。
  3. 搜索結果必須按照經緯度位於附近位置。
  4. 搜索結果必須按最後一次激活排序。

要顯示搜索,我需要用戶名,圖片,城市和國家,年齡,性別和離線/在線狀態。

我有一個查詢,按位置順序:

SELECT 
    latitude, longitude, 
    SQRT(POW(69.1 * (latitude - 52.58) , 2) + POW(69.1 * (- 1.12 - longitude) * COS(latitude/57.3) , 2)) AS distance 
FROM 
    location 
ORDER BY 
    distance 

任何人都可以有助於建立這些條件codeignitor查詢?

+0

當你說「codeigniter查詢」是否指使用其活動記錄類的人?因爲您上面發佈的查詢只是一般性的SQL查詢而不是特定的codeigniter。 – fire 2011-12-22 09:17:56

+0

是的我正在尋找quesry在活躍的記錄,我張貼一般查詢提供線索..跳躍這將有助於。 – 2011-12-22 09:30:13

+0

其中離線/在線商店的狀態在db,你知道如何搜索經緯度附近的位置 – Dau 2011-12-22 10:50:10

回答

0

你可以嘗試建立一個圍繞這個查詢

select l.latitude, l.longitude, 
SQRT(POW(69.1 * (l.latitude - 52.58) , 2) + 
POW(69.1 * (- 1.12 - l.longitude) * COS(l.latitude/57.3) , 2)) as distance 
from user as u 
left join profile as p 
on p.user_id = u.id 
left join location as l 
on l.user_id = u.id 
where u.activated=1 and u.banned=0 
order by distance desc 

我建議你查找在MySQL中使用外鍵約束

0

有這取決於你需要如何準確的是其他一些optmizations的以及你需要多快。我不會告訴你如何做到這一點就在這裏,但是這是基本的CodeIgniter查詢你問:

$max_distance = 20; 

$this->db 
    ->select('*') // Change this to only the fields you need... 
    ->select('SQRT(POW(69.1 * (latitude - 52.58) , 2) + POW(69.1 * (- 1.12 - longitude) * COS(latitude/57.3) , 2)) AS distance') 
    ->from('user') 
    ->where('user.active', 1) 
    ->where('user.banned !=', 0) 
    ->where('distance <', $max_distance) 
    ->join('location','location.user_id=user.user_id') 
    ->join('profile','profile.user_id=user.user_id') 
    ->order_by('last_active','desc') 
    ->get(); 

請注意,距離計算,一旦慢如您有記錄的幾十萬而成。最明顯的優化是首先用一個框限制查詢,以減少必須計算遠處不存在的行的距離,然後在該範圍內執行半徑。

+0

首先感謝您提供這一點。我試圖調試查詢,但得到錯誤您的SQL語法有錯誤;檢查與您的MySQL服務器版本相對應的手冊,以便在'FROM('user')JOIN'location'附近使用正確的語法。'location'.'user_id' ='user'.'user_id' JOIN'pro'at line 2 – 2011-12-22 18:33:13