我想使用此查询将一些字段输出到文件中:
SELECT
CONCAT('[',
GROUP_CONCAT(
CONCAT(CHAR(13), CHAR(9), '{"name":"', name, '",'),
CONCAT('"id":', CAST(rid AS UNSIGNED), '}')
),
CHAR(13), ']')
AS json FROM `role`
INTO OUTFILE '/tmp/roles.json'
在输出文件中,我得到如下内容:
[
\ {"name":"anonymous user","rid":1},
\ {"name":"authenticated user","rid":2},
\ {"name":"admin","rid":3},
\ {"name":"moderator","rid":4}
]
如您所见,换行符 ( char(13)
) 没有反斜杠,但制表符 ( char(9)
) 有。我怎样才能摆脱它们?
更新 Sundar G 给了我一个提示,所以我将查询修改为:
SELECT
CONCAT('"name":', name),
CONCAT('"rid":', rid)
INTO outfile '/tmp/roles.json'
FIELDS TERMINATED BY ','
LINES STARTING BY '\t{' TERMINATED BY '},\n'
FROM `role`
我不知道为什么,但是这种语法从输出文件中去除了反斜杠:
{"name":"anonymous user","rid":1},
{"name":"authenticated user","rid":2},
{"name":"admin","rid":3},
{"name":"moderator","rid":4}
这已经是相当不错的输出,但我还想在文件的开头和结尾添加左方括号和右方括号。我可以通过 MySQL 语法来做到这一点还是我必须手动做到这一点?