[英]MySQL - How can I list all key names of a JSON data from column
I have a SQL table and that contains a JSON column.我有一个 SQL 表,其中包含一个 JSON 列。 Now, I want to do that.
现在,我想这样做。 How get the all key names from registered all rows (JSON column).
如何从注册的所有行(JSON 列)中获取所有键名。 An example;
一个例子;
ID JSON
1 {"a": 1, "b": 2}
2 {"apple": 3, "banana": 5}
3 {"wood": 4, "food": 6}
I should have got a query that get all key names from this rows.我应该得到一个查询,从这些行中获取所有键名。 So my result should be that;
所以我的结果应该是这样;
JSON
--------
a
b
apple
banana
wood
food
Is that possible?那可能吗? Can I do this?
我可以这样做吗?
To answer your question, YES it is possible.要回答您的问题,是的,这是可能的。
To answer your second question: How would I know if you can dot this?回答你的第二个问题:我怎么知道你是否可以点这个?
Below is an example of how to do it:以下是如何执行此操作的示例:
First i created the sample table:首先我创建了示例表:
CREATE TABLE json2(id integer, js JSON);
INSERT INTO json2 VALUES
( 1, '{"a": 1, "b": 2}'),
( 2, '{"apple": 3, "banana": 5}'),
( 3, '{"wood": 4, "food": 6}');
When applying some JSON functions :应用一些JSON 功能时:
SELECT
JSON_UNQUOTE(JSON_EXTRACT(JSON_KEYS(js),CONCAT('$[',x.x,']'))) as `JSON`
FROM json2
CROSS JOIN (SELECT 0 as x
UNION ALL
SELECT 1
) x
;
The output is: output 是:
+ --------- +
| JSON |
+ --------- +
| a |
| b |
| apple |
| banana |
| food |
| wood |
+ --------- +
You can use a recursive cte:您可以使用递归 cte:
with recursive cte(i, val, r) as (
select id, substr(js, instr(js, '"')+1, instr(js, ':') - instr(js, '"')-2), substr(js, instr(js, ':')+1, instr(js, '}') - instr(js, ':')) from json
union all
select i, substr(r, instr(r, '"')+1, instr(r, ':') - instr(r, '"')-2), substr(r, instr(r, ':')+1, instr(r, '}') - instr(r, ':')) from cte where r like '%"%'
)
select val `JSON` from cte order by i;
Output: Output:
JSON
-------
a
b
apple
banana
wood
food
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.