带有数据和标题的MySQL CSV导出

时间:2018-05-09 18:09:41

标签: mysql mariadb

我也尝试使用Header从MySQL数据库导出CSV。但我收到以下错误 -

ERROR 1222 (21000): The used SELECT statements have a different number of columns

MySQL查询如下 -

SELECT * FROM (
  (SELECT COLUMN_NAME
    FROM INFORMATION_SCHEMA.COLUMNS
    WHERE TABLE_NAME = 'ORDERS'
    AND TABLE_SCHEMA = 'REMOTE'
    ORDER BY ORDINAL_POSITION)
  UNION ALL
  (SELECT * FROM ORDERS WHERE orderDate>='2018-05-07')) AS TBL
INTO OUTFILE 'C:/xampp/htdocs/WES/DBScript/SS_Orders.csv'
FIELDS TERMINATED BY ','
ENCLOSED BY '"'
LINES TERMINATED BY '\n';

1 个答案:

答案 0 :(得分:0)

通常你必须这样做:

SELECT *
FROM (
    select 'A', 'B', 'C'
    union all
    select a, b, c from table
    ) t
INTO OUTFILE [...]

请注意,您必须确保所有列数据类型都正确匹配,这意味着它们都需要是varchar或类似的。

对于标题,您可以通过以下方式自动化它们:

SELECT * FROM (
SELECT MAX(CASE WHEN ORDINAL_POSITION = 1 THEN COLUMN_NAME END),
    MAX(CASE WHEN ORDINAL_POSITION = 2 THEN COLUMN_NAME END),
    MAX(CASE WHEN ORDINAL_POSITION = 3 THEN COLUMN_NAME END),
    MAX(CASE WHEN ORDINAL_POSITION = 4 THEN COLUMN_NAME END),
    MAX(CASE WHEN ORDINAL_POSITION = 5 THEN COLUMN_NAME END),
    MAX(CASE WHEN ORDINAL_POSITION = 6 THEN COLUMN_NAME END),
    [...]
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = 'ORDERS'
    AND TABLE_SCHEMA = 'REMOTE'
UNION ALL
SELECT [...]
) t
INTO OUTFILE [...]

但是你仍然需要知道列的数量。如果你想动态地做,那基本上需要动态SQL。

It may be easier to just write a Python script to do it