V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
MySQL 5.5 Community Server
MySQL 5.6 Community Server
Percona Configuration Wizard
XtraBackup 搭建主从复制
Great Sites on MySQL
Percona
MySQL Performance Blog
Severalnines
推荐管理工具
Sequel Pro
phpMyAdmin
推荐书目
MySQL Cookbook
MySQL 相关项目
MariaDB
Drizzle
参考文档
http://mysql-python.sourceforge.net/MySQLdb.html
I2E
V2EX  ›  MySQL

求助 mysql 查询优化

  •  
  •   I2E · 14 天前 · 796 次点击

    表 abc_http_detail_log_2024_04_13 为网络日志表,包含部分字段:

    uid int	// 用户 id
    account_id int // 子账号 id
    flow bingint // 量消耗
    ip char // 本机 ip
    address varchar // 请求地址
    

    联合索引 idx_uid_account_ip 包含字段 uid, account_id, ip

    现在需要查询当日的用户流量使用情况。account_id 可以为 0 或者大于 0 。

    表 abc_http_detail_log_2024_04_13 有 2075w 条数据,uid=114708 的数据量最多,有 637w 条。在统计流量消耗时出现上图的情况。如何才能优化查询呢?

    10 条回复    2024-04-17 16:08:35 +08:00
    YouZiAndDanJuan
        1
    YouZiAndDanJuan  
       14 天前
    分表
    I2E
        2
    I2E  
    OP
       14 天前
    有两点疑问:
    1 ,为什么加了 account_id > 0 会导致第二条 sql 的索引失效
    2 ,为什么加了 limit 索引又会生效
    I2E
        3
    I2E  
    OP
       14 天前
    @YouZiAndDanJuan 分表要改很多屎山代码
    bianhui
        4
    bianhui  
       14 天前
    无语,你看看字只看一半么,using index 和 using inex condition 是两个东西。百度搜下索引下推。
    xlzyxxn
        5
    xlzyxxn  
       14 天前
    @I2E #2 应该有个 uid 、account_id 、flow 的联合索引吧,第二条查询条件 adress 需要回表,uid=114708 占了大部分数据的情况下,mysql 认为不如直接去全表扫描。第三条查询不需要回表。
    jshfsym42
        6
    jshfsym42  
       13 天前
    第二条 SQL 匹配的行数太多了,MySQL 执行器认为不如全盘扫描;可以看看这个。
    https://dev.mysql.com/doc/refman/8.0/en/table-scan-avoidance.html
    You are using a key with low cardinality (many rows match the key value) through another column. In this case, MySQL assumes that by using the key probably requires many key lookups and that a table scan would be faster.
    8355
        7
    8355  
       13 天前
    account_id+ 一般索引
    你的日志表在查询某一个 id 的时候跳行太多了,加上某 uid 和 account_id orderby 即可。
    coderzhangsan
        8
    coderzhangsan  
       13 天前
    能说下 mysql 版本吗?版本不同,可能导致优化的结果也是不同的。
    I2E
        9
    I2E  
    OP
       12 天前
    I2E
        10
    I2E  
    OP
       12 天前
    @jshfsym42 应该是这个原因
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   1121 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 25ms · UTC 18:24 · PVG 02:24 · LAX 11:24 · JFK 14:24
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.