我正在尝试优化查询,但当我在子查询中使用变量时,未使用索引。
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)
...
我得到了解释
+----+-------------+-------+------+---------------+-----+---------+-----+----------+----------------------------------------------------+
| id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra |
+----+-------------+-------+------+---------------+-----+---------+-----+----------+----------------------------------------------------+
| 1 | PRIMARY | clog | ALL | | | | | 40978775 | Using where; Using join buffer (Block Nested Loop) |
+----+-------------+-------+------+---------------+-----+---------+-----+----------+----------------------------------------------------+
如果不使用变量,而是运行查询并将其替换为字符串,例如:
...
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')
...
解释
给我:
+----+-------------+-------+--------+---------------+---------+---------+------+------+-------------+
| id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra |
+----+-------------+-------+--------+---------------+---------+---------+------+------+-------------+
| 1 | PRIMARY | clog | eq_ref | PRIMARY | PRIMARY | 4 | func | 1 | Using where |
+----+-------------+-------+--------+---------------+---------+---------+------+------+-------------+
我已经检查了这里的其他答案,尝试强制转换变量,convert_tz到UTC,使用时间戳(日期,时间)创建它,日期格式... 我的想法已经用完了。
date_create 的类型为:
date_create TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL,
为什么会发生这种情况?既然我使用的是 PK 的 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)
关于mysql - 子查询中的变量不使用时间戳字段中的索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48358794/