如何从mysql数据库的所有表中删除特定的行?

gk7wooem  于 2021-06-17  发布在  Mysql
关注(0)|答案(2)|浏览(365)

我有一个名为 my_db . 中的每个表 my_db 有一列 set_id 它的值从2140到2180。我想把所有的table都翻一遍 my_db 并删除其中的行 set_id 大于2170。我该怎么做?

cuxqih21

cuxqih211#

我想,这不是一个问题,但你可以这样做

SELECT CONCAT('delete from my_db.',table_name,' where set_id > 270') FROM information_schema.tables where table_schema='my_db';

结果就是所有需要运行的查询。你可以复制并运行它。

vvppvyoh

vvppvyoh2#

我喜欢马可的答案,因为它很短,提供了一个很好的解决办法。这就是我使用过程、while循环和prepared语句所想到的。不需要复制。
它检索并存储到一个临时表中,然后遍历每个表名并执行单独的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;

注意:我使用的是MySQL5.7.23版本。

相关问题