我正在尝试使用 Oracle 12.1.0.2 中引入的新 JSON 特性
但是,我似乎找不到在 JSON 文档中的数组中查找特定值的方法。
考虑下表和数据:
create table orders
(
id integer not null primary key,
details clob not null check (details is json (strict))
);
insert into orders (id, details) values
(1, '{"products": [{ "product": 1, "quantity": 5}, {"product": 2, "quantity": 1}], "delivery_address": "My hometown"}');
insert into orders (id, details) values
(2, '{"products": [{ "product": 42, "quantity": 1}, {"product": 10, "quantity": 2}], "comment": "Your website is too slow"}');
insert into orders (id, details) values
(3, '{"products": [{ "product": 543, "quantity": 1}], "discount": "15"}');
insert into orders (id, details) values
(4, '{"products": [{ "product": 738, "quantity": 12}], "discount": "32"}');
现在我正在尝试编写一个返回所有订单的 SQL 查询,其中订购了产品 #2。
我不能用
json_exists
因为它不允许数组表达式(无论如何我都不知道如何指定值)。json_value
只返回一个值,所以我不能“迭代”数组值。我试过:
select *
from orders o
where json_value(details, '$.products[*].product') = '2';
但这并没有返回任何东西。
我也试过
json_table
,但这似乎也只从数组中获取第一个元素:select *
from orders o,
json_table(o.details, '$' columns (product_id integer path '$.products[*].product')) t
where t.product_id = 2;
但这并没有显示任何东西。显然,“array_step ”中的“星形扩展”不会扩展
json_table
中的值。所以我的问题是:
我如何(基于上述示例数据)检索已订购编号为 2 的产品的所有订单?
我本质上是在寻找与此 Postgres 查询等效的内容:
select *
from orders
where details @> '{"products": [{"product": 2}] }';
最佳答案
我现在没有任何可用的 oracle 安装,但我相信 json_table 中的第一个字符串应该是我们想要从中生成行的数组的路径。
然后在 COLUMNS 中,路径应该相对于数组,而不是根。
尝试这个:
select *
from orders o,
json_table(o.details, '$.products[*]'
columns (
product_id integer path '$.product'
)
) t
where t.product_id = 2;
关于sql - 在 Oracle 中搜索 JSON 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29898750/