我有3个表用户,配置文件和位置。这些表的结构如下:
user
table
user_id | email | pass | activated | banned
profile
表
user_id | name | birthday | picture | gender | last_active
location
表
user_id | city | country | latitude | longitude
现在这里是搜索条件:
- 用户必须激活(1)才能出现在搜索结果中。
- 用户不能被禁止(0)。
- 搜索结果必须是附近位置根据经纬度。
- 搜索结果必须按最后一次活动排序。
显示搜索我将需要用户名,图片,城市和国家,年龄,性别和离线/在线状态。
我有一个按位置排序的查询:
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查询吗?
你可以尝试构建这个查询
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
还有许多其他优化,这取决于您需要的准确性和速度。我不会在这里向您展示如何做到这一点,但这是您所询问的基本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();
请注意,当您有数十万条记录时,距离计算就会变慢。最明显的优化是首先用一个方框限制查询,以减少必须计算不在附近的行的距离,然后在其中执行半径。