SQL 查询拼接字段输出 JSON 格式
原始数据
mysql> select * from capacity;
+----+----------+------------+---------------------+
| id | capacity | date | time |
+----+----------+------------+---------------------+
| 1 | 180 | 2019-10-26 | 2019-10-30 09:34:48 |
| 2 | 190 | 2019-10-27 | 2019-10-30 09:34:48 |
| 3 | 200 | 2019-10-28 | 2019-10-30 09:34:48 |
| 4 | 210 | 2019-10-29 | 2019-10-30 09:34:48 |
| 5 | 224 | 2019-10-30 | 2019-10-30 09:34:48 |
+----+----------+------------+---------------------+
5 rows in set (0.01 sec)
1
2
3
4
5
6
7
8
9
10
11
2
3
4
5
6
7
8
9
10
11
- 输出 JSON
SELECT
CONCAT('[',
GROUP_CONCAT(
CONCAT('{"capacity":',capacity),
CONCAT(',"date":"',date),'"}')
,']')
AS json FROM capacity;
| [{"capacity":180,"date":"2019-10-26"},{"capacity":190,"date":"2019-10-27"},{"capacity":200,"date":"2019-10-28"},{"capacity":210,"date":"2019-10-29"},{"capacity":224,"date":"2019-10-30"}] |
1
2
3
4
5
6
7
8
9
10
2
3
4
5
6
7
8
9
10
需要加上 set session group_concat_max_len = 1073741824;
,防止数据截断
CONCAT 函数 是拼接多个字段和字符串的 GROUP_CONCAT 函数 是分组拼接多个字段字符串的,一般和 group by 一起用
想变成文件,重定向即可。
reference
- [1] hpfive. 直接从MySql导出表数据为JSON数据open in new window