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

时间:2018-07-27 08:44:59

标签: mysql phpmyadmin export-to-csv information-schema

我想将数据库中的每个表导出到由commom列对所有表排序的单独的csv文件中。我正在使用MySql,phpMyAdmin和Windows 10

我是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;

其他方法也都很好

谢谢!

1 个答案:

答案 0 :(得分:0)

你在那儿。

一种解决方案是使用带有游标的存储过程来获取表名,并使用一些动态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_file_priv),并且应该将yrcolname更改为适当的值。