mysql>
show variables like
'%scheduler%';+
-----------------+-------+
| variable_name |
value|+
-----------------+-------+
| event_scheduler |
off|
+-----------------+-------+
1row
inset
-- 臨時開啟
setglobal event_scheduler =on;
-- 永久開啟,my.cnf中[mysqld]新增,並重啟服務
event_scheduler=
on
-- task_history:表名,start_time:日期字段
delete
from task_history where
date
(start_time)
<=
date
(date_sub(
now(),
interval
2day))
;
create event del_task_history on schedule every 1
daydo
delete
from compare.task_history where
date
(start_time)
<=
date
(date_sub(
now(),
interval
2day))
;
-- 建立儲存過程,先use database_name;
delimiter
// create
procedure del_task_history(
)begin
delete
from task_history where
date
(start_time)
<=
date
(date_sub(
now(),
interval
2day))
;end
//delimiter
;-- 檢視儲存過程
select
*from mysql.
proc
where db=
'資料庫名'
;-- 呼叫儲存過程
call del_task_history();
-- 刪除儲存過程
drop
procedure
ifexists del_task_history;
-- 建立event
create event del_task_history
on schedule
every 1
day
starts '2020-10-01 00:00:00'
on completion not preserve enable
docall del_task_history(
);
-- 開啟某事件
alter event del_task_history on completion preserve enable
;-- 關閉某事件
alter event del_task_history on completion preserve disable
;
-- 查詢event列表
show events;
-- 根據event名稱查詢
show
create event del_task_history;
-- 查詢執行記錄
select
*from information_schema.events;
select
*from mysql.event;
drop event if
exists del_task_history;
儲存過程一般不能以表名作為引數,不然會報錯,所以採用prepare
方式.
-- 引數1:要刪除的表, 引數2:時間戳列名, 引數3:刪除多少天前的資料
delimiter
// create
procedure delete_table_data(
in table_name varchar(50
),in column_name varchar(50
),in interval_day int
)begin
set@statements
= concat(
'delete from '
,table_name,
' where date('
,column_name,
') <= date(date_sub(now(),interval '
,interval_day,
' day))');
prepare stmt from
@statements
;execute stmt;
deallocate
prepare stmt;
end//
delimiter
;-- 呼叫
call delete_table_data(
't_test'
,'create_time',90
);
MySQL定時任務刪除資料
前提 表中有date defualt current timestamp 字段 基礎語句 檢視定時事件執行緒是否開啟 show variables like event scheduler 開啟定時事件執行緒 set global event scheduler 1 檢視已有的定時事件任務 show...
MySQL刪除資料
mysql通過delete從表中刪除 去掉 資料。可以從表中刪除特定的行或者從表中刪除所有的行。下面語句是從customer表中刪除一行 delete from customers where cust id 10006 先檢視表customers在刪除前的成員 select cust id,cus...
MySQL 刪除資料
從資料表中刪除資料使用 delete 語句,delete 語句允許用 where 子句指定刪除條件。語法格式 delete from table name where table name 要執行刪除操作的表 where 為可選引數,用於指定刪除條件,如果沒有 where 子句,將刪除表中的所有記錄...