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

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日