简体   繁体   English

SQL 查找元素在 JSON 数组列中

[英]SQL find elements is in JSON array column

Hello i have a column table who contains json array with tags in it, I try to find a way to select result who contain some of values in it :您好,我有一个列表,其中包含带有标签的 json 数组,我尝试找到一种方法来选择其中包含一些值的结果:

ID ID tags标签
1 1 ["test01"] [“test01”]
2 2 ["test02","test03"] ["test02","test03"]

I try to used JSON_QUERY AND JSON_VALUE() :我尝试使用JSON_QUERY AND JSON_VALUE()

SELECT *
FROM table_tags  
WHERE JSON_QUERY(tags,'$') IN ('test01', 'test02')

return nothing什么都不回

but with json_value on the first array element [0]但是在第一个数组元素 [0] 上有 json_value

SELECT *
FROM table_tags  
WHERE JSON_VALUE(tags,'$[0]') IN ('test01', 'test02')

it return the first one with test01它用 test01 返回第一个

ID ID tags标签
1 1 ["test01"] [“test01”]

i need to find a way to iterate through json_value tags to find all tags in ('test01', 'test02')我需要找到一种方法来遍历 json_value 标签以查找 ('test01', 'test02') 中的所有标签

You need an OPENJSON() call to parse the stored JSON array.您需要一个OPENJSON()调用来解析存储的 JSON 数组。 The result is a table with columns key , value and type and in the value column is each element from the parsed JSON array.结果是一个包含keyvaluetype列的表, value列中是解析的 JSON 数组中的每个元素。 The column data type is nvarchar(max) with the same collation as tags column collation.列数据类型是nvarchar(max) ,其排序规则与tags列排序规则相同。

SELECT *
FROM (VALUES
   (1, '["test01"]'),
   (2, '["test02","test03"]')
) table_tags (id, tags)
WHERE EXISTS (
   SELECT 1 FROM OPENJSON(tags) WHERE [value] IN ('test01', 'test02')
)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM