应该如何有效创建索引 或者 如何优化呢?
select od.DishId,DishName,od.Price,od.TimePrice,DishDiscount,DishTypeId,DishMode,OrderDishId,MainDishId,od.DelayTime,OperationTime,od.State,Count,IsCancel,DepId
from TOrder as o
inner join TOrderDish as od on o.OrderId=od.OrderId
inner join TDish as d on od.DishId=d.DishId
where o.BranchId=73 and OrderTime>='2019-06-01 09:00:00 '
and OrderTime<='2019-07-01 08:59:59 ' and o.State=2;
以上语句执行用时20多秒!!!
TOrder表已经有索引,有37131条数据
主键是OrderId
Idx_Unique_OrderName索引列是 BranchId和OrderName
Idx_BrIdOrdTime索引列是 BranchId和OrderTime
TOrderDish表有索引, 有319130条数据
主键是OrderDishId
Index_TOrderDish索引列是 OrderId
TDish表,有2077条数据
主键是DishId
Idx_BrIdOrdTime索引列是 BranchId,OrderTime,State
尝试不连表 和连1个表的速度比较一下
将TOrder表索引列改为BranchId、State和OrderTime,并将它设置为索引
select OrderId
from TOrder
where BranchId=73 and State=2
and OrderTime>='2019-06-01 09:00:00 ' and OrderTime<='2019-07-01 08:59:59 '
单个表这样执行查询很快,用时才0.073秒
@默者: 你可以尝试连表 改为三个单表查 ,速度应该是比较快的. 就是代码多了点.
先过滤,在连接
select od.DishId,DishName,od.Price,od.TimePrice,DishDiscount,DishTypeId,DishMode,OrderDishId,MainDishId,od.DelayTime,OperationTime,od.State,Count,IsCancel,DepId from( (select * from TOrder where BranchId=73 and State=2 and OrderTime>='2019-06-01 09:00:00 ' and OrderTime<='2019-07-01 08:59:59 ' )as o inner join TOrderDish as od on o.OrderId=od.OrderId inner join TDish as d on od.DishId=d.DishId ) as t
不行,按照你提出这种方式测试了一下,同样还是执行慢,执行有时17秒
而且我还给TOrder表增加了 索引,索引列是BranchId,State,OrderTime
执行语句是
ALTER TABLE TOrder ADD INDEX Idx_Test(BranchId,State,OrderTime);
@默者: 按理说你这个数据量不大,就是不加索引也不会这么慢,我们之前也遇到过一个查询慢的原因是:主键的编码不一致,比如一个是utf8,另一个是utf8mb4,连接的时候就特别慢。你只能分别看看连接前和连接后的用时,找到慢的原因。
@~冰: TOrder表主键编码是utf8_general_ci、TOrderDish表外键OrderId编码也是utf8_general_ci,没有发现不同