qq_41265012 2018-06-30 03:28 采纳率: 70%
浏览 1681
已采纳

mysql这样的复合查询应该怎么创建索引

select * from (SELECT * FROM 表 where fenlei in(1,2) and ispc=1 order by id desc) T WHERE T.fenlei in(1,2) and T.month>0 group by T.fenlei order by T.month desc LIMIT 0,20

创建了fenlei和ispc的单独索引和联合索引,但是还是扫描全表了。

  • 写回答

5条回答 默认 最新

  • lqhfut2000 2018-06-30 04:29
    关注

    下面用几个例子对比查询条件的不同对性能影响.

    create table test(
    a int,
    b int,
    c int,
    KEY a(a,b,c)
    );

    优: select * from test where a=10 and b>50
    差: select * from test where a50

    优: select * from test where order by a
    差: select * from test where order by b
    差: select * from test where order by c

    优: select * from test where a=10 order by a
    优: select * from test where a=10 order by b
    差: select * from test where a=10 order by c

    优: select * from test where a>10 order by a
    差: select * from test where a>10 order by b
    差: select * from test where a>10 order by c

    优: select * from test where a=10 and b=10 order by a
    优: select * from test where a=10 and b=10 order by b
    优: select * from test where a=10 and b=10 order by c

    优: select * from test where a=10 and b=10 order by a
    优: select * from test where a=10 and b>10 order by b
    差: select * from test where a=10 and b>10 order by c

    索引原则

    1.索引越少越好
    原因:主要在修改数据时,第个索引都要进行更新,降低写速度。
    2.最窄的字段放在键的左边
    3.避免file sort排序,临时表和表扫描.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(4条)

报告相同问题?

问题事件

  • 已采纳回答 7月28日

悬赏问题

  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!
  • ¥15 drone 推送镜像时候 purge: true 推送完毕后没有删除对应的镜像,手动拷贝到服务器执行结果正确在样才能让指令自动执行成功删除对应镜像,如何解决?
  • ¥15 求daily translation(DT)偏差订正方法的代码
  • ¥15 js调用html页面需要隐藏某个按钮
  • ¥15 ads仿真结果在圆图上是怎么读数的
  • ¥20 Cotex M3的调试和程序执行方式是什么样的?
  • ¥20 java项目连接sqlserver时报ssl相关错误
  • ¥15 一道python难题3
  • ¥15 牛顿斯科特系数表表示