我有一个名为my_db
的数据库。
my_db
中的每个表都有一列set_id
,其值在2140到2180之间。我想遍历my_db
中的所有表并删除行set_id
大于2170。我该怎么做?
答案 0 :(得分:1)
我认为,这不是对此的查询,但是您可以执行以下操作
SELECT CONCAT('delete from my_db.',table_name,' where set_id > 270') FROM information_schema.tables where table_schema='my_db';
其结果是您需要运行的所有查询。您可以复制并运行它。
答案 1 :(得分:0)
我喜欢Marco的答案,因为它简短易懂,并且提供了一种不错的解决方法。这就是我使用“过程”,“同时循环”和“预准备语句”提出的。无需复制。
它检索并将其存储到一个临时表中,然后遍历每个表名并执行单独的DELETE语句。
DROP PROCEDURE IF EXISTS myPurge;
-- Will be used to signify the end of the procedure
DELIMITER ;;
-- Use a procedure
CREATE PROCEDURE myPurge()
BEGIN
-- Retrieve tables from information_schema and
-- Store them into a temporary table
DROP TABLE IF EXISTS tempTables;
CREATE TEMPORARY TABLE tempTables
SELECT table_name FROM information_schema.tables WHERE table_schema = 'my_db';
-- Initialise variables
SET @i = 0;
SELECT COUNT(*) FROM tempTables INTO @n;
-- Loop from 0 to number of rows
WHILE @i < @n DO
-- Retrieve table from row @i
-- SELECT * FROM tempTables LIMIT @i, 1 INTO @atable; -- doesn't seem to work on MySQL v5
-- Prepare and execute a subsidiary query
SELECT CONCAT("SELECT * FROM tempTables LIMIT ", @i, ",1 INTO @atable") INTO @preLimStmt;
PREPARE limStmt FROM @preLimStmt;
EXECUTE limStmt;
-- Save statement into temporary variable
-- HERE we prepare your PURGE
SELECT CONCAT("DELETE FROM my_db.", @atable, " WHERE set_id > 2170") INTO @preStmt;
-- Prepare and execute the purge statement
PREPARE stmt FROM @preStmt;
EXECUTE stmt;
-- Increment @i
SET @i = @i + 1;
END WHILE;
END;;
-- Call the procedure
CALL myPurge();
-- cleanup
DEALLOCATE PREPARE limStmt;
DEALLOCATE PREPARE stmt;
-- Reset to default
DELIMITER ;
-- Remove the temporary table
DROP TABLE tempTables;
注意:我正在使用MySQL版本5.7.23。