› 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
xing393939
V2EX  ›  MySQL

mysql的复杂查询如何建索引?

  •  
  •   xing393939 ·
    xing393939 · Jan 28, 2013 · 4256 views
    This topic created in 4992 days ago, the information mentioned may be changed or developed.
    SELECT * FROM feeds WHERE user_id=249229547 AND status < 10000 AND ((act_pid = 0 AND cat = 3) OR act_pid > 0) and is_friends = 0



    这个查询怎么建索引,测试(user_id,status,act_pid,cat,is_friends)无效
    9 replies  •  1970-01-01 08:00:00 +08:00
    eric_zyh
        1
    eric_zyh  
       Jan 28, 2013
    (user_id,status,is_friends)
    或 (user_id,status,is_friends,act_pid,cat)
    plprapper
        2
    plprapper  
       Jan 28, 2013
    中间的OR逻辑 括号部分 从sql中拆出去吧,别放在sql里做。建索引除了sql外还和你的数据分布情况有关系。
    xing393939
        3
    xing393939  
    OP
       Jan 29, 2013
    @eric_zyh 无效

    @plprapper 如何拆分呢
    techzhou
        4
    techzhou  
       Jan 29, 2013
    这个你不把explain贴出来么
    keakon
        5
    keakon  
       Jan 29, 2013
    把equal关系放前面啊,我估计执行时先查了is_friends,而不是status
    Cadina
        6
    Cadina  
       Jan 29, 2013
    索引只看equal最大前缀,只有索引最后一个field用大于或小于才能完整利用索引
    xing393939
        7
    xing393939  
    OP
       Jan 29, 2013
    @Cadina 那如何优化这个查询?
    ipconfiger
        8
    ipconfiger  
       Jan 29, 2013
    都不用看Explain的结果

    or 直接就导致索引失效了

    (SELECT * FROM feeds WHERE user_id=249229547 AND status < 10000 AND act_pid = 0 AND cat = 3 and is_friends = 0) union all (SELECT * FROM feeds WHERE user_id=249229547 AND status < 10000 AND act_pid > 0 and is_friends = 0)

    这样子拆成2个子查询再union all 加起来就不会丢索引了
    ipconfiger
        9
    ipconfiger  
       Jan 29, 2013
    另外,mysql在一个查询里头只能match一个索引,所以你需要根据使用的顺序 将 user_id,status,act_pid和is_friends合起来建一个联合索引才能在4个条件里都match上索引

    自己explain试试就知道了
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Privacy   ·   Solana   ·   979 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 39ms · UTC 19:10 · PVG 03:10 · LAX 12:10 · JFK 15:10
    ♥ Do have faith in what you're doing.