问题
I need a way to run a SQL command and then export the results to a JSON formatted text file.
I have this link: https://falseisnotnull.wordpress.com/2014/11/23/creating-json-documents-with-mariadb/
But I don't understand the CREATE_COLUMN section of his statement, nor really the terminology he uses to understand how it relates to my DB.
Can anyone please simplify his example for me on a query like this?
SELECT * FROM thisismy.database;
If I do the above with the INTO OUTFILE command, I get data that looks like this:
1 Armand Warren 56045 Taiwan, Province of China 0 0
2 Xenos Salas 71090 Liberia 0 0
3 Virginia Whitaker 62723 Nicaragua 0 0
4 Kato Patrick 97662 Palau 0 0
5 Cameron Ortiz P9C5B6 Eritrea 0 0
But I need it to look like this:
{ "aaData": [
[ "1", "Armand", "Warren", "56045", "Taiwan, Province of China" ],
[ "2", "Xenos", "Salas", "71090", "Liberia" ],
[ "3", "Virginia", "Whitaker", "62723", "Nicaragua" ],
[ "4", "Kato", "Patrick", "97662", "Palau" ],
[ "5", "Cameron", "Ortiz", "P9C 5B6", "Eritrea" ]
] }
Any suggestions?
Thanks
Edit: I run MariaDB if that helps
回答1:
SELECT CONCAT('[\n\t', GROUP_CONCAT(
COLUMN_JSON(
COLUMN_ADD(
COLUMN_CREATE('id', id)
, 'name', name
, 'price', price
)
)
ORDER BY id
SEPARATOR ',\n\t'
), '\n]') AS json
FROM product \G
Ignore everything except COLUMN_CREATE. This is where the JSON creation is happening. OK, so we have:
COLUMN_JSON(
COLUMN_ADD(
COLUMN_CREATE('id', id)
, 'name', name
, 'price', price
)
)
COLUMN_ADD is the function that adds the columns to the JSON. Each argument is a key paired with its value. So 'name' is what the key in the JSON object will be and name is what the value will be. In this case it's the column name from the table product.
So, let's say you want to query your users table and get their first names, last names, and ID. This is what your query would look like:
SELECT CONCAT('[\n\t', GROUP_CONCAT(
COLUMN_JSON(
COLUMN_ADD(
COLUMN_CREATE('id', id)
, 'first_name', first_name
, 'last_name', last_name
)
)
ORDER BY id
SEPARATOR ',\n\t'
), '\n]') AS json
FROM users \G
And at the end of the COLUMN_JSON command we have AS json, which casts it as the JSON type you want.
来源:https://stackoverflow.com/questions/45364453/export-sql-query-to-json-formatted-text-file