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