我有一个非规格化的VIEW
,我们将其称为VIEW_X
,它看起来像下面的样子(它只是一个普通的简单视图-未实现或类似的东西):
ID GROUP_ID PART_1_ID PART_2_ID
1 1723189 cd69f0f4-a5ed-4196-916d-401e98ffec75 X1
1 1723189 cd69f0f4-a5ed-4196-916d-401e98ffec75 X2
2 1723185 8d5132cb-1b6e-4e79-9698-fd1962eb808f K1
2 1723188 a191cb01-32ac-4ab4-bd6b-3ef777e395ca K1
它被非规范化,因为它实际上代表了这样的结构:
{
id: 1,
group_id: 1723189,
part_1_id: 'cd69f0f4-a5ed-4196-916d-401e98ffec75'
part_2_ids: ["X1", "X2"]
}
此视图中的PART_2_ID
是从JSON_TABLE
中进行选择的结果,其中原始表中的数据存储在类似["X1", "X2"]
的数组中:
JSON_TABLE(a.PART_2_IDS, '$' COLUMNS (
NESTED PATH '$[*]'
COLUMNS (
PART_2_ID VARCHAR2(4000) PATH '$'
)
)) p2
在此视图上运行这样的查询时,尽管预期结果是ID
为2
的单个结果,但我得到0个结果:
SELECT ID
FROM VIEW_X
WHERE PART_2_ID IN ('K1')
GROUP BY ID
HAVING COUNT(DISTINCT(PART_2_ID)) = 1
ID
--
(no results)
图1
很奇怪,如果仅执行以下操作,我会得到预期的两个结果,因为有两行与ID
2
匹配,其中PART_2_ID
上的匹配项为K1
:
SELECT ID
FROM VIEW_X
WHERE PART_2_ID IN ('K1')
ID
--
2
2
但是,如果我运行以下两个查询之一,则会在ID
1
上找到匹配项:
SELECT ID
FROM VIEW_X
WHERE PART_2_ID IN ('X1')
GROUP BY ID
HAVING COUNT(DISTINCT(PART_2_ID)) = 1
ID
--
1
SELECT ID
FROM VIEW_X
WHERE PART_2_ID IN ('X1', 'X2')
GROUP BY ID
HAVING COUNT(DISTINCT(PART_2_ID)) = 2
ID
--
1
我不明白为什么 图1 没有返回预期的结果-我在忽略什么吗?这与JSON_TABLE
的工作方式有关吗?
答案 0 :(得分:2)
我无法在以下位置复制它:
Oracle Database 12c Enterprise Edition Release 12.1.0.2.0 - 64bit Production
;或Oracle Database 18c Enterprise Edition Release 18.0.0.0.0 - Production
Oracle设置:
CREATE TABLE table1 ( document CLOB CONSTRAINT ensure_json CHECK (document IS JSON) );
INSERT INTO table1 ( document ) VALUES ( '{"id":1,"group_id":1723189,"part_1_id":"cd69f0f4-a5ed-4196-916d-401e98ffec75","part_2_ids":["X1","X2"]}' );
INSERT INTO table1 ( document ) VALUES ( '{"id":2,"group_id":1723185,"part_1_id":"8d5132cb-1b6e-4e79-9698-fd1962eb808f","part_2_ids":["K1"]}' );
INSERT INTO table1 ( document ) VALUES ( '{"id":2,"group_id":1723188,"part_1_id":"a191cb01-32ac-4ab4-bd6b-3ef777e395ca","part_2_ids":["K1"]}' );
CREATE VIEW VIEW_X AS
SELECT p.*
FROM table1 t
CROSS JOIN
JSON_TABLE(
t.document,
'$'
COLUMNS (
id PATH '$.id',
group_id PATH '$.group_id',
part_1_id PATH '$.part_1_id',
NESTED PATH '$.part_2_ids[*]'
COLUMNS (
PART_2_ID VARCHAR2(4000) PATH '$'
)
)
) p;
查询1 :
SELECT *
FROM VIEW_X;
结果:
ID GROUP_ID PART_1_ID PART_2_ID
---------- ---------- ------------------------------------ ---------
1 1723189 cd69f0f4-a5ed-4196-916d-401e98ffec75 X1
1 1723189 cd69f0f4-a5ed-4196-916d-401e98ffec75 X2
2 1723185 8d5132cb-1b6e-4e79-9698-fd1962eb808f K1
2 1723188 a191cb01-32ac-4ab4-bd6b-3ef777e395ca K1
查询2 :
SELECT ID
FROM VIEW_X
WHERE PART_2_ID IN ('K1')
GROUP BY ID
HAVING COUNT(DISTINCT(PART_2_ID)) = 1;
结果:
ID
--
2