Mysql 子查询中的变量未使用时间戳字段中的索引
我试图优化查询,但当我在子查询中使用变量时,索引没有被使用Mysql 子查询中的变量未使用时间戳字段中的索引,mysql,sql,performance,Mysql,Sql,Performance,我试图优化查询,但当我在子查询中使用变量时,索引没有被使用 set @dh = '2018-01-17 23:59:59' ... inner join cons c1 on c1.idcons = xx.maxcons left join conslog clog on clog.idconslog = (select max(clt.idconslog) from conslog clt
set @dh = '2018-01-17 23:59:59'
...
inner join cons c1 on c1.idcons = xx.maxcons
left join conslog clog on clog.idconslog = (select max(clt.idconslog)
from conslog clt
where clt.idcons = c1.idcons
and clt.date_create <= @dh)
...
如果不使用变量,而是运行查询,将其替换为字符串,如:
...
inner join cons c1 on c1.idcons = xx.maxcons
left join conslog clog on clog.idconslog = (select max(clt.idconslog)
from conslog clt
where clt.idcons = c1.idcons
and clt.date_create <= '2018-01-17 23:59:59')
...
我在这里检查了其他答案,所以,尝试转换变量,将_tz转换为UTC,使用timestampdate、time、date\u格式创建它。。。
我的点子快用完了
创建日期的类型为:
date_create TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL,
为什么会发生这种情况?既然我使用的是idcons,它为什么要检查这么多行呢
感谢您的帮助不如这样做,简化流程,只获取您需要的记录。我认为clog.idcons=c1.idcons可能会有帮助 我认为将嵌套查询更改为使用clog可能也会有所帮助,因为它是与嵌套=
left join conslog clog on clog.idcons=c1.idcons and clog.idconsumolog = (select max(clt.idconslog)
from conslog clt
where clog.idcons = clt.idcons
and clt.date_create <= @dh)
“创建日期”列的数据类型是什么?用数据类型更新了我的问题。这是个好主意,你试过了吗TIMESTAMP@dhYes,我试过了。从文档:此函数将日期或日期时间表达式expr作为日期时间值返回。因为这是一个不同的类型从列它必须铸造它。。。显然,这个解决方案解决了这个问题,因为它使用idcons索引。但是它并没有完全回答这个问题,因为我仍然不知道为什么变量会影响性能
date_create TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL,
left join conslog clog on clog.idcons=c1.idcons and clog.idconsumolog = (select max(clt.idconslog)
from conslog clt
where clog.idcons = clt.idcons
and clt.date_create <= @dh)