【问题标题】:Complex codeigniter user search query复杂的 codeigniter 用户搜索查询
【发布时间】:2011-12-22 08:27:17
【问题描述】:

我有 3 个表用户、个人资料和位置。这些表的结构是:

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 查询吗?

【问题讨论】:

  • 当您说“codeigniter 查询”时,您的意思是使用他们的活动记录类吗?因为您在上面发布的查询只是一般的 SQL 查询,而不是 codeigniter 特定的。
  • 是的,我正在寻找活动记录中的查询,我发布了一般查询以提供线索。希望这会有所帮助。
  • 离线/在线状态在哪里存储在db中,你知道如何搜索附近经纬度的位置
  • @Hemant 我在个人资料表中通过 last_active 在线/离线,我提供了一般查询以搜索附近
  • 好的,你知道如何搜索附近经纬度的位置吗

标签: php mysql codeigniter


【解决方案1】:

你可以尝试围绕这个查询构建

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 中使用 外键 约束查找

【讨论】:

    【解决方案2】:

    还有许多其他优化,具体取决于您需要的准确度和速度。我不会在这里向您展示如何执行此操作,但这是您所询问的基本 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();
    

    请注意,一旦您有数十万条记录,距离计算就会变慢。最明显的优化是首先用一个框限制查询,以减少必须计算距离不近的行的距离,然后在其中计算半径。

    【讨论】:

    • 首先感谢您提供此服务。我尝试调试查询但收到错误您的 SQL 语法有错误;检查与您的 MySQL 服务器版本相对应的手册以获取正确的语法,以便在 'FROM (user) JOIN location ON location.user_id=user.user_id JOIN `pro' at line 附近使用正确的语法2
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-01-23
    • 2012-10-18
    • 1970-01-01
    • 2021-05-30
    • 1970-01-01
    • 2012-05-15
    • 1970-01-01
    相关资源
    最近更新 更多