2011-12-22 80 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