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

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

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

cuxqih21

cuxqih211#

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

  1. 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语句。

  1. DROP PROCEDURE IF EXISTS myPurge;
  2. -- Will be used to signify the end of the procedure
  3. DELIMITER ;;
  4. -- Use a procedure
  5. CREATE PROCEDURE myPurge()
  6. BEGIN
  7. -- Retrieve tables from information_schema and
  8. -- Store them into a temporary table
  9. DROP TABLE IF EXISTS tempTables;
  10. CREATE TEMPORARY TABLE tempTables
  11. SELECT table_name FROM information_schema.tables WHERE table_schema = 'my_db';
  12. -- Initialise variables
  13. SET @i = 0;
  14. SELECT COUNT(*) FROM tempTables INTO @n;
  15. -- Loop from 0 to number of rows
  16. WHILE @i < @n DO
  17. -- Retrieve table from row @i
  18. -- SELECT * FROM tempTables LIMIT @i, 1 INTO @atable; -- doesn't seem to work on MySQL v5
  19. -- Prepare and execute a subsidiary query
  20. SELECT CONCAT("SELECT * FROM tempTables LIMIT ", @i, ",1 INTO @atable") INTO @preLimStmt;
  21. PREPARE limStmt FROM @preLimStmt;
  22. EXECUTE limStmt;
  23. -- Save statement into temporary variable
  24. -- HERE we prepare your PURGE
  25. SELECT CONCAT("DELETE FROM my_db.", @atable, " WHERE set_id > 2170") INTO @preStmt;
  26. -- Prepare and execute the purge statement
  27. PREPARE stmt FROM @preStmt;
  28. EXECUTE stmt;
  29. -- Increment @i
  30. SET @i = @i + 1;
  31. END WHILE;
  32. END;;
  33. -- Call the procedure
  34. CALL myPurge();
  35. -- cleanup
  36. DEALLOCATE PREPARE limStmt;
  37. DEALLOCATE PREPARE stmt;
  38. -- Reset to default
  39. DELIMITER ;
  40. -- Remove the temporary table
  41. DROP TABLE tempTables;

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

展开查看全部

相关问题