› 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 · Apr 15, 2024 · 3167 views
    This topic created in 948 days ago, the information mentioned may be changed or developed.

    表 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 replies  •  2024-04-17 16:08:35 +08:00
    YouZiAndDanJuan
    YouZiAndDanJuan
    Apr 15, 2024
    1
    分表
    I2E
    I2E
    OP
    Apr 15, 2024
    2
    有两点疑问:
    1 ,为什么加了 account_id > 0 会导致第二条 sql 的索引失效
    2 ,为什么加了 limit 索引又会生效
    I2E
    I2E
    OP
    Apr 15, 2024
    3
    @YouZiAndDanJuan 分表要改很多屎山代码
    bianhui
    bianhui
    Apr 15, 2024
    4
    无语,你看看字只看一半么,using index 和 using inex condition 是两个东西。百度搜下索引下推。
    xlzyxxn
    xlzyxxn
    Apr 15, 2024
    5
    @I2E #2 应该有个 uid 、account_id 、flow 的联合索引吧,第二条查询条件 adress 需要回表,uid=114708 占了大部分数据的情况下,mysql 认为不如直接去全表扫描。第三条查询不需要回表。
    jshfsym42
    jshfsym42
    Apr 16, 2024
    6
    第二条 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
    8355
    Apr 16, 2024
    7
    account_id+ 一般索引
    你的日志表在查询某一个 id 的时候跳行太多了,加上某 uid 和 account_id orderby 即可。
    coderzhangsan
    coderzhangsan
    Apr 16, 2024
    8
    能说下 mysql 版本吗?版本不同,可能导致优化的结果也是不同的。
    I2E
    I2E
    OP
    Apr 17, 2024
    9
    I2E
    I2E
    OP
    Apr 17, 2024
    10
    @jshfsym42 应该是这个原因
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Privacy   ·   Solana   ·   4761 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 34ms · UTC 02:59 · PVG 10:59 · LAX 18:59 · JFK 21:59
    ♥ Do have faith in what you're doing.