如何在MYSQL中将结果集转换为Json
select id,name,age from person where id=1;
此查询给出如下结果
id | name | age
1 |manoj | 20
我想要一个像下面这样的 JSON
I want a JSON like below
"{"id":1,"name":"manoj","age":5}"
我想要一种动态方式.当我尝试从另一个表中进行另一个查询时,结果就像以前的 JSON
I want a dynamic way.When I try another query from another table ,that result as like previous JSON
我想从一个表中生成 JSON 并存储到 MYSQL 中的一个列中,我不想使用 php 或其他服务器端语言来生成这个 JSON.
I want to generate JSON from a table and store into a column in MYSQL, I don't want to use php or other server side language for generate this JSON.
如何在 MYSQL 中获取 JSON?
How can I get JSON in MYSQL ?
使用 JSON_OBJECT()
函数:
SELECT JSON_OBJECT('id', id, 'name', name, 'age', age)
FROM person
WHERE id = 1;
这至少需要 MySQL 5.7 或 MariaDB 10.2.3,那时添加了所有与 JSON 相关的功能.
This requires at least MySQL 5.7 or MariaDB 10.2.3, that's when all the JSON-related functions were added.
如果您不想将列名硬编码到查询中,则需要编写一个创建动态 SQL 的存储过程,使用 INFORMATION_SCHEMA.COLUMNS
获取所有列名字.
If you don't want to hard-code the column names into the query, you'll need to write a stored procedure that creates dynamic SQL, using INFORMATION_SCHEMA.COLUMNS
to get all the column names.