在 INTO OUTFILE 中使用 concat() 给我错误代码 1064

Using concat() in INTO OUTFILE gives me error code 1064

我正在尝试执行查询并将其结果导出到文件名中格式为 current_timestamp 的 csv 文件。

我觉得 INTO OUTFILE 很烦人,除了一个简单的字符串之外别无所求,希望我是错的。有人对此有任何见解吗?

SELECT
    COUNT(*) AS AgentCount,
    clients.ClientId,
    clients.Name AS ClientName,
    computers.RouterAddress
FROM
    computers
LEFT JOIN 
    clients
ON
    computers.ClientId = clients.ClientId
GROUP BY
    computers.RouterAddress
ORDER BY
    AgentCount DESC 
INTO OUTFILE 
    CONCAT('C:\ProgramData\MySQL\MySQL Server 5.6\Uploads\', DATE_FORMAT(CURRENT_TIMESTAMP, '%Y-%m-%d_%H%i%s'), '.csv')
FIELDS TERMINATED BY 
    ','
ENCLOSED BY 
    '"'
LINES TERMINATED BY 
    '\r\n'
正如您所发现的,

select ... into outfile 不支持变量。您要求的内容需要动态 SQL:

SET @sql = CONCAT_WS('\r\n',
    'SELECT',
    '   COUNT(*) AS AgentCount,',
    '   clients.ClientId,',
    '   clients.Name AS ClientName,',
    '   computers.RouterAddress',
    'FROM',
    '   computers',
    'LEFT JOIN',
    '   clients',
    'ON',
    '   computers.ClientId = clients.ClientId',
    'GROUP BY',
    '   computers.RouterAddress',
    'ORDER BY',
    '   AgentCount DESC',
    CONCAT('INTO OUTFILE \'', TRIM(BOTH '\'' FROM QUOTE(@@secure_file_priv)), DATE_FORMAT(CURRENT_TIMESTAMP, '%Y-%m-%d_%H%i%s'), '.csv\''),
    'FIELDS TERMINATED BY \',\'',
    'ENCLOSED BY \'\"\'',
    'LINES TERMINATED BY \'\r\n\'');

    PREPARE statement FROM @sql;

    EXECUTE statement;
    DEALLOCATE PREPARE statement;