如何从存储在MariaDB表多行TEXT列中的JSON数组中检索JSON值的唯一列表

hgtggwj0  于 2022-11-08  发布在  其他
关注(0)|答案(1)|浏览(169)

我目前在MariaDB数据库(版本10.4)中名为'orders'的表中名为'tax_components'的TEXT列中存储了一个JSON对象数组,如下所示:
第1行

[
{"tax_type":"Vat 15","tax_percentage":"15.00","tax_amount":"13.04"},
{"tax_type":"Tobacco","tax_percentage":"100.00","tax_amount":"50.00"},
{"tax_type":"Exempt","tax_percentage":"0.00","tax_amount":"0.00"},
{"tax_type":"Zero","tax_percentage":"0.00","tax_amount":"0.00"}
]

第二行

[
{"tax_type":"Vat","tax_percentage":"15.00","tax_amount":"52.17"},
{"tax_type":"Exempt","tax_percentage":"0.00","tax_amount":"0.00"},
{"tax_type":"Tobacco Tax","tax_percentage":"0.00","tax_amount":"0.00"}
]

我有多个行的值与上表中的值类似。
上面的JSON数组在不同的行中有不同的值,有时tax_type = 'Tobacco',有时tax_type =“Tobacco Tax”,有时没有。
有人能告诉我写什么SQL查询来提取所有tax_type值和相应的tax_percentage的唯一列表吗?这些值和相应的tax_percentage存储在“tax_components”列的所有行的所有JSON数组中。
先谢谢你。

n3ipq98p

n3ipq98p1#

WITH RECURSIVE
cte AS (
    SELECT id, val, 1 element, 
           JSON_UNQUOTE(JSON_EXTRACT(val, '$[0].tax_type')) tax_type, 
           JSON_UNQUOTE(JSON_EXTRACT(val, '$[0].tax_percentage')) tax_percentage, 
           JSON_UNQUOTE(JSON_EXTRACT(val, '$[0].tax_amount')) tax_amount
    FROM test
    UNION ALL
    SELECT id, val, 1 + element, 
           JSON_UNQUOTE(JSON_EXTRACT(val, CONCAT('$[', element, '].tax_type'))), 
           JSON_UNQUOTE(JSON_EXTRACT(val, CONCAT('$[', element, '].tax_percentage'))), 
           JSON_UNQUOTE(JSON_EXTRACT(val, CONCAT('$[', element, '].tax_amount')))
    FROM cte
    WHERE element < JSON_LENGTH(val)
)
SELECT id, tax_type, tax_percentage, tax_amount 
FROM cte

如果您需要某个明确JSON属性的唯一值,则从CTE中删除不需要的属性表达式,删除id并将DISTINCT添加到外部查询中。
https://dbfiddle.uk/?rdbms=mariadb_10.4&fiddle=c1baff9748ab9be320052a73258951c8

相关问题