0

我正在使用 MySQL 表。

样品表EMPprimary_key(EID, DOJ)):

姓名 开斋节 部门 萨尔瓦多 司法部 (YYYY-MM-DD)
一种 6 ee 2000 2021-03-01
5 2020 2021-04-30
C 3 2000 2020-12-27
D 4 简历 2020 2020-10-31
1 2000 2021-01-01
F 2 空值 2021-02-28
G 7 ee 空值 2020-11-20

我有一项工作可以将数据删除并插入到类似结构的表中。

该过程需要删除非月度数据。也就是说,它将删除带有EID 6, 3, 1, 7: 这些行DOJ不是month-end 的行。

我提出的查询:

-- DOJ is of type DATE
DELETE FROM EMP WHERE LAST_DAY(DOJ) <> DOJ ;

它按预期工作。但是,因为有大量数据(约 500 万),所以速度很慢。

我知道由于功能的原因,LAST_DAY()我正在失去index. DOJ您能否建议我如何改进查询?

4

2 回答 2

2

您对索引的看法是正确的。在这里没有用。想到的唯一想法是生成一个列,告诉您日期是否为月末。因此,您将拥有一个可以索引并在查询中使用的列:

create table emp 
(
  ename varchar(100),
  ...
  doj date,
  is_month_end bool as (doj = last_day(doj))
);

create index idx_month_ends on emp (is_month_end);

delete from emp where not is_month_end;

演示:https ://dbfiddle.uk/?rdbms=mysql_8.0&fiddle=397388b70bb1f459bbefce630ad27ac4

但是,如果这只是表中数据的一小部分,例如 1%,则索引只能提供帮助。由于要删除更多行,因此阅读整个表更有意义。

于 2021-02-12T15:15:42.433 回答
-1
Where (month(doj) in (9,4,6,11) and day(doj) <> 30) or
      (month(doj) in (1,3,5,7,8,10,12) and day(doj) <> 31) or
      (month(doj) in (2) and day(doj) not in(28,29))

? 你可以调整一下 2 月

于 2021-02-12T14:55:11.517 回答