问题
I have a database table like this:
Then I want to read data as json object like this:
{
"date_time":"02102019",
"ma_vi_tri":
{
"1a":222,
"0a":111,
"2a":333
}
}
I use this SQL command like this:
MariaDB [mqtt]> SELECT json_object('date_time',date_time,'ma_vi_tri',ma_vi_tri, 'PH', PH) FROM PH where date_time='02102019';
But result output not like I wish.
Thank you in advance.
回答1:
One option (be careful with performance problems):
SELECT
CONCAT(
'{"date_time": "', `date_time`, '", "ma_vi_tri": ',
REPLACE(
GROUP_CONCAT(
JSON_OBJECT(`ma_vi_tri`, `PH`)
),
'},{',
', '
),
'}'
) `JSON`
FROM
`PH`
WHERE
`date_time` = '02102019'
GROUP BY
`date_time`;
See dbfiddle.
回答2:
You can create a multi dimensional array and use json_encode
Example:
$ma_vi_tri_arr['1a'] = "222";
$ma_vi_tri_arr['0a'] = "111";
$ma_vi_tri_arr['2a'] = "333";
$result['date_time'] = "02102019";
$result['ma_vi_tri'] = $ma_vi_tri_arr;
echo(json_encode($result));
来源:https://stackoverflow.com/questions/58231149/how-to-read-mysql-data-as-json