在MariaDB 10.2.19中,我有一个名为forms
的表,该表的列template
始终包含对象的JSON数组。其中一些对象将具有我想返回的属性:name
(应始终存在),rule
和parameters
。我该如何从整个数组中仅返回这三个属性,而只返回存在rule
的对象呢?
一个示例数组(格式化以便于查看):
[{
"label": "Employed?",
"class": "select",
"name": "employed",
"parameters": "Yes",
"rule": "in"
},
{
"label": "Breed of dog?",
"class": "select",
"name": "breed",
"parameters": "spaniel, collie, mix",
"rule": "in"
},
{
"label": "Number",
"class": "text",
"name": "breed"
}]
答案 0 :(得分:1)
如果您使用的是MySQL 8.0.4或更高版本,则一种方法是使用JSON_TABLE
:
mysql> SELECT * FROM foo;
+-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| data |
+-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| [{"name": "employed", "rule": "in", "class": "select", "label": "Employed?", "parameters": "Yes"}, {"name": "breed", "rule": "in", "class": "select", "label": "Breed of dog?", "parameters": "spaniel, collie, mix"}, {"name": "breed", "class": "text", "label": "Number"}] |
+-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
1 row in set (0,00 sec)
mysql> SELECT name, parameters
FROM foo,
JSON_TABLE (
foo.data,
"$[*]" COLUMNS (
name VARCHAR(100) PATH "$.name",
rule VARCHAR(100) PATH "$.rule",
parameters VARCHAR(100) PATH "$.parameters")
) AS t
WHERE rule IS NOT NULL;
+----------+----------------------+
| name | parameters |
+----------+----------------------+
| employed | Yes |
| breed | spaniel, collie, mix |
+----------+----------------------+
2 rows in set (0,00 sec)
https://dev.mysql.com/doc/refman/8.0/en/json-table-functions.html
答案 1 :(得分:0)
您可以使用专用的numbers_table
表来完成此操作:
SELECT
JSON_VALUE(f.template,CONCAT('$[',n.number,'].name')) AS `name`,
JSON_VALUE(f.template,CONCAT('$[',n.number,'].rule')) AS `rule`,
JSON_VALUE(f.template,CONCAT('$[',n.number,'].parameters')) AS `parameters`
FROM forms AS f
JOIN numbers_table AS n
WHERE
n.number < JSON_LENGTH(f.template) AND
JSON_VALUE(f.template,CONCAT('$[',n.number,'].rule')) IS NOT NULL;
numbers_table
表包含一个名为number
的列,该列从0
开始,并且可以根据您的用例需要而定(我有1000个值0
到{ {1}})。将999
字段的每个元素提取到其自己的行中非常有用。
第一个JSON_ARRAY
条件确保我们使用的数字与WHERE
中的元素数量一样(在您的情况下为JSON_ARRAY
)。
根据您的用例,第二个template
条件消除了没有WHERE
的情况。