如果我在表中有以下几行:
clientId settings
1 {"franchises":[1,7,9,11,14,20,23,26,27,29,33,34,35,45,49,50,57,58,72,73]}
2 {"franchises":[1]}
3 {"franchises":[50]}
我将如何查询以提取拥有特许经营权 1 或 50 的客户 ID?
我试着做
SELECT clientId FROM clientSettings WHERE JSON_VALUE(settings, '$.franchises') IN (1,50)
但这没有用。
最佳答案
您可以使用 json 函数:
select distinct c.clientId
from clientSettings c
cross apply openjson(c.settings, '$.franchises') with (franchise integer '$')
where franchise in (1, 50);
将其包装在
exists
中可能会表现得更好,因为它避免了聚合的需要:select c.clientId
from clientSettings c
where exists (
select 1
from openjson(c.settings, '$.franchises') with (franchise integer '$')
where franchise in (1, 50)
)
Demo on DB Fiddle (我在你的数据集中添加了一条不匹配的行,id 为
4
):|客户 ID |
| -------: |
| 1 |
| 2 |
| 3 |
关于sql - 检查一个或多个 id 是否在 json 字符串中,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/60197104/