Alisa, I'm assuming that you are using the naming convention temp_1, temp_2 to indicate that you intend to delete these tables after only a short time and that these are not TEMPORARY tables as surmised by @anton.
A few points to note ab:out the example below:
It's written as an event but you could easily turn it into a procedure which would allow you to pass in different interval values or database name.
You'll need to use a cursor to fetch the table names and dynamic SQL to prepare and execute statements to drop the tables and delete the records in cached_tbl
.
I've made it a little more complex than strictly necessary to illustrate how you could create and populate a TEMPORARY table in one statement which would be useful if you did turn this into a procedure. You can simplify it by declaring the cursor as the the statement in @sql1 and removing the prepare and execute on stmt1.
You probably want to be a bit more restrictive in selecting tables otherwise you run the risk of deleting cached_tbl
or other database tables by accident.
DELIMITER //
CREATE EVENT prune
ON SCHEDULE
EVERY 1 DAY
DO
BEGIN
DECLARE done BOOLEAN DEFAULT FALSE;
DECLARE tname VARCHAR(64);
DECLARE cur CURSOR FOR SELECT * FROM `tables_tmp`;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE;
SET @sql1 =
'CREATE TEMPORARY TABLE `tables_tmp`
SELECT `table_schema`,`table_name`
FROM `information_schema`.`tables`
WHERE `table_schema` = ''db''
AND `table_name` LIKE ''temp_%''
AND `create_time` < (NOW() - INTERVAL 1 DAY)';
PREPARE stmt1 FROM @sql1;
EXECUTE stmt1;
DEALLOCATE PREPARE stmt1;
OPEN cur;
myloop:LOOP
FETCH cur INTO tname;
IF done = TRUE THEN
LEAVE myloop;
END IF;
SET @sql2 = CONCAT('DROP TABLE IF EXISTS `db`.`', tname , '`;');
PREPARE stmt2 FROM @sql2;
EXECUTE stmt2;
DEALLOCATE PREPARE stmt2;
SET @sql3 = CONCAT('DELETE FROM `cached_tbl` WHERE `table_name` = ''', tname , ''';');
PREPARE stmt3 FROM @sql3;
EXECUTE stmt3;
DEALLOCATE PREPARE stmt3;
END LOOP;
END //
DELIMITER ;