如何从按公共列排序的数据库中导出所有表?

5ktev3wc  于 2021-06-20  发布在  Mysql
关注(0)|答案(1)|浏览(313)

我想将数据库中的每个表导出到一个单独的csv文件中,并按commom列对所有表进行排序。我使用的是mysql、phpmyadmin和windows10
我是mysql的新手,在stackoverflow上搜索,我可以得到以下代码,将一个表导出为csv文件,完全符合我的要求:

SELECT * INTO OUTFILE 'c://path/name_of_table.csv'
FIELDS TERMINATED BY ',' 
OPTIONALLY ENCLOSED BY '' 
LINES TERMINATED BY '\n' 
FROM `name_of_table` ORDER BY name_of_column;

我可以在上面的查询中使用表名作为变量来迭代特定数据库中的所有表吗?
比如:

FOREACH my_table IN my_database

    SELECT * INTO OUTFILE 'c://path/' .my_table.table_name. '.csv'
    FIELDS TERMINATED BY ',' 
    OPTIONALLY ENCLOSED BY '' 
    LINES TERMINATED BY '\n' 
    FROM `my_table.table_name` ORDER BY name_of_column;

END FOREACH;

任何其他的方法也很好
谢谢!

c9qzyr3d

c9qzyr3d1#

你已经走到一半了。
一种解决方案是使用带有游标的存储过程来获取表名,并使用一些动态sql来生成select into outfile语句。
这样的办法应该行得通。

DELIMITER //

DROP PROCEDURE IF EXISTS db_export_csv //
CREATE PROCEDURE db_export_csv(_path VARCHAR(255), _sname VARCHAR(64))
BEGIN
  DECLARE tname VARCHAR(64);
  DECLARE done BOOLEAN DEFAULT FALSE;

  DECLARE cur CURSOR FOR 
    SELECT `table_name`
    FROM `information_schema`.`tables`
    WHERE `table_schema` = _sname
    AND `table_type` = 'BASE TABLE';

  DECLARE CONTINUE HANDLER FOR SQLSTATE '02000' SET done = TRUE;
  OPEN cur;

  myloop: LOOP
    FETCH cur INTO tname;
    IF done THEN 
      LEAVE myloop; 
    END IF;

    SET @sql = CONCAT("SELECT * INTO OUTFILE \'" , _path , '' , tname , '_' , CURRENT_DATE , ".csv\' ",
      "FIELDS TERMINATED BY ',' ", 
      "OPTIONALLY ENCLOSED BY '''' ",
      "LINES TERMINATED BY '\n' ", 
      "FROM `" , _sname , "`.`" , tname , "` ORDER BY `yrcolname` ASC");

    PREPARE stmt FROM @sql;
    EXECUTE stmt;
    DEALLOCATE PREPARE stmt;

  END LOOP; 

END //

DELIMITER ;

CALL db_export_csv('/var/lib/mysql-files/', 'test');

显然,我已经在linux上测试过了,所以您可以将自己的可写路径放进去(允许设置@@global.secure\u file\u priv),然后应该更改 yrcolname 到适当的值。

相关问题