我有大型数据库,每月使用以下查询进行修剪。但是,我有数百个表,并且希望将其放入数据库中每个表的foreach循环中。
我知道如何在PHP中实现此循环,但是最好在纯SQL中将其作为查询直接运行在数据库上。
以noprune
为前缀的表(例如noprune_master_tableZ
)需要放在循环之外。
我从哪里开始?谢谢
START TRANSACTION;
set @N := (now());
CREATE TABLE master_tableA_snapshot AS SELECT * FROM master_tableA where insertDATE < date_sub(@N,INTERVAL 32 DAY);
SELECT * from master_tableA_snapshot INTO OUTFILE '/tmp/master_tableA_snapshot_TODAYSDATE.csv' FIELDS TERMINATED BY ',' ENCLOSED BY '"' LINES TERMINATED BY '\n';
DELETE from master_tableA where insertDATE < date_sub(@N,INTERVAL 32 DAY);
DROP TABLE master_tableA_snapshot;
COMMIT;
答案 0 :(得分:0)
您实际上只有两个语句,其帮助变量简化为:
set @N := date_sub(NOW(),INTERVAL 32 DAY);
SELECT *
FROM master_tableA
WHERE insertDATE < @N
INTO OUTFILE '/tmp/master_tableA_snapshot_TODAYSDATE.csv'
FIELDS TERMINATED BY ',' ENCLOSED BY '"' LINES TERMINATED BY '\n';
DELETE from master_tableA where insertDATE < @N;
PHP通过查询选择表名:
SELECT TABLE_NAME
FROM information_schema.TABLES
WHERE SCHEMA='mydatabase'
AND TABLE_NAME NOT LIKE 'noprune%';