我试图优化查询但是当我在子查询中使用变量时,索引没有被使用。
Future
我选择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)
...
explain
如果不是使用变量,而是运行查询,将其替换为字符串,如:
+----+-------------+-------+------+---------------+-----+---------+-----+----------+----------------------------------------------------+
| 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')
...
给了我:
explain
我已经在SO上检查了其他答案,尝试强制将变量 convert_tz 改为UTC,使用时间戳(日期,时间)创建 DATE_FORMAT ... 我的想法已经不多了。
date_create的类型为:
+----+-------------+-------+--------+---------------+---------+---------+------+------+-------------+
| 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 |
+----+-------------+-------+--------+---------------+---------+---------+------+------+-------------+
为什么会这样?为什么必须检查这么多行,因为我使用 idcons 这是PK?
感谢您的帮助
答案 0 :(得分:1)
相反如何,简化唯一获取所需的记录。我认为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)