为什么此SQL不使用Date类型列使用索引
mySQL:5.7/8.0
表DDL
-- auto-generated definition
create table test_date_index
(
id int auto_increment primary key,
account_id int not null,
remark varchar(10) null,
cal_date date null,
constraint cal_date_index
unique (cal_date, account_id)
);
在这种情况下不使用索引
explain
select *
from test_date_index
where (account_id, cal_date) in (
select account_id, max(cal_date) from test_date_index group by account_id
);
,而是在这种情况下工作,
explain
select *
from test_date_index
where (account_id, cal_date) in (
select account_id, '2022-04-18' from test_date_index group by account_id
)
我认为这是因为cal_date
列的类型,但我找不到有关此的任何文档
mysql:5.7/8.0
table ddl
-- auto-generated definition
create table test_date_index
(
id int auto_increment primary key,
account_id int not null,
remark varchar(10) null,
cal_date date null,
constraint cal_date_index
unique (cal_date, account_id)
);
in this case not using index
explain
select *
from test_date_index
where (account_id, cal_date) in (
select account_id, max(cal_date) from test_date_index group by account_id
);
but work in this case
explain
select *
from test_date_index
where (account_id, cal_date) in (
select account_id, '2022-04-18' from test_date_index group by account_id
)
i think this is because of the type of the cal_date
column but i can't find any doc about this
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您正在使用什么版本?在5.7之前,“行构造函数”没有优化。但是,缺乏最佳指数可能是造成迟钝的主要原因。
对于第一个查询...
重写“ GroupWise-Max”查询因此:
获取
unique
索引:以该顺序使用这些列。需要首先在我使用的“派生”查询(子查询)中有用,需要首先。而且,这往往是组织桌子的更好方法。
您的第二个查询表明,它可以使用您的向后索引,并且在您正在运行的版本中优化了“行构造器”。
What version are you using? Before 5.7, "row constructors" were not optimized. However, the lack of the optimal index may be the main cause of sluggishness.
For the first query...
Rewrite the "groupwise-max" query thus:
Get promote the
UNIQUE
index to this:with those columns in that order. Specificaly,
account_id
needs to be first in order to be useful in the "derived" query (subquery) that I used. Also, it tends to be a better way to organize the table.Your second query shows that it can use your backward index and that 'row constructors' are optimized in the version you are running.