簡體   English   中英

子查詢中的變量未在時間戳字段中使用索引

[英]Variable in subquery not using index in timestamp field

我正在嘗試優化查詢,但是當我在子查詢中使用變量時,未使用索引。

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給我:

+----+-------------+-------+--------+---------------+---------+---------+------+------+-------------+
| 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 |
+----+-------------+-------+--------+---------------+---------+---------+------+------+-------------+

我已經在SO上檢查了其他答案,嘗試變量convert_tz轉換為UTC,使用timestamp(date,time), date_format創建它...我已經筋疲力盡了。

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)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM