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 metadata提取的PDF元数据,如何转换为一个Excel
  • ¥15 关于arduino编程toCharArray()函数的使用
  • ¥100 vc++混合CEF采用CLR方式编译报错
  • ¥15 coze 的插件输入飞书多维表格 app_token 后一直显示错误,如何解决?
  • ¥15 vite+vue3+plyr播放本地public文件夹下视频无法加载
  • ¥15 c#逐行读取txt文本,但是每一行里面数据之间空格数量不同
  • ¥50 如何openEuler 22.03上安装配置drbd
  • ¥20 ING91680C BLE5.3 芯片怎么实现串口收发数据
  • ¥15 无线连接树莓派,无法执行update,如何解决?(相关搜索:软件下载)
  • ¥15 Windows11, backspace, enter, space键失灵