• 请不要在回答技术问题时复制粘贴 AI 生成的内容
gaojiangouyu
V2EX  ›  程序员

访客记录表去重,有什么比较好的方法?

  •  
  •   gaojiangouyu · Dec 13, 2020 · 2323 views
    This topic created in 2002 days ago, the information mentioned may be changed or developed.

    数据库:MySQL 现状:有一个访客历史表,(id,uid,visitor_id,visit_datetime) visit_history

    需求:查询一个用户主页历史被访问记录,同一个访客如果多次访问则只展示最新的一比记录

    sql:

    select u.* from visit_history u
    join(select max(id) id from visit_history where uid = xxx group by visitor_id) um on u.id = um.id
    

    这个查询由于需要对 visitor_id 进行去重(即便在 uid 上建立了相关索引)导致性能及其低下,mysql 有办法处理这种查询吗?

    5 replies    2020-12-14 14:36:50 +08:00
    rekulas
        1
    rekulas  
       Dec 13, 2020
    没看懂什么操作 取最新的直接 order 取不就行了 强行加个 group 再 join 是为啥呢
    crclz
        2
    crclz  
       Dec 13, 2020
    看看那条查询的性能分析
    wangritian
        3
    wangritian  
       Dec 14, 2020
    主表直接 group by visitor_id 试试?
    换个角度,多次访问只做 update,确保只存在一条记录,在业务上是否允许?
    qyqx5538
        4
    qyqx5538  
       Dec 14, 2020
    select t.id,t.uid,max(t.visit_datetime) from visit_history t group by t.uid order;
    高版本的 mysql 可能会因为 ONLY_FULL_GROUP_BY 的约束报错。
    telami
        5
    telami  
       Dec 14, 2020
    select * from (select * from visit_history where uid = 1 ORDER BY visit_datetime desc limit 99999999) GROUP BY visitor_id;
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   864 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 41ms · UTC 22:01 · PVG 06:01 · LAX 15:01 · JFK 18:01
    ♥ Do have faith in what you're doing.