在给定 JSONB 中以逗号分隔的字符串的情况下,在另一个 table 中查询匹配 属性
Query matching property in another table given a comma-separated string in JSONB
我想在另一个 table B 中查找 属性,其中源是 table A 的 JSONB 列中逗号分隔字符串的一部分。
create table option
(
optionid bigint not null primary key,
attributevalues jsonb default '{}'::jsonb
);
create table district
(
districtid bigint not null primary key,
uid varchar(11) not null,
name varchar(230) not null unique
);
INSERT into option values (1, '{"value": "N8UXIAycxy3,uVwyu3R4nZG,fuja8k8PCFO,y0eUmlYp7ey", "attribute": {"id": "K54wAf6EX0s"}}'::jsonb);
INSERT INTO district (districtid, uid, name) VALUES
(1, 'N8UXIAycxy3', 'district1'),
(2, 'uVwyu3R4nZG', 'district2'),
(3, 'fuja8k8PCFO', 'district3'),
(4, 'y0eUmlYp7ey', 'district4');
我可以将所有项目拆分为 ,
,但我如何“加入”以查找名称(例如 N8UXIAycxy3
--> district1
)?
我尝试以传统方式“加入”,但这行不通,因为 district_uid
无法访问这样的查询:
SELECT UNNEST(STRING_TO_ARRAY(co.attributevalues #>> '{"K54wAf6EX0s", "value"}', ',')) AS district_uid
FROM option o
JOIN district d on district_uid = d.uid;
我想要查询结果:district1,district2,district3,district4
。这是可能的还是我需要一个循环?
您需要将逗号分隔的字符串转换为数组,即 attributevalues->>'value'
:
select name
from option
cross join unnest(string_to_array(attributevalues->>'value', ',')) as district_uid
join district on uid = district_uid
我想在另一个 table B 中查找 属性,其中源是 table A 的 JSONB 列中逗号分隔字符串的一部分。
create table option
(
optionid bigint not null primary key,
attributevalues jsonb default '{}'::jsonb
);
create table district
(
districtid bigint not null primary key,
uid varchar(11) not null,
name varchar(230) not null unique
);
INSERT into option values (1, '{"value": "N8UXIAycxy3,uVwyu3R4nZG,fuja8k8PCFO,y0eUmlYp7ey", "attribute": {"id": "K54wAf6EX0s"}}'::jsonb);
INSERT INTO district (districtid, uid, name) VALUES
(1, 'N8UXIAycxy3', 'district1'),
(2, 'uVwyu3R4nZG', 'district2'),
(3, 'fuja8k8PCFO', 'district3'),
(4, 'y0eUmlYp7ey', 'district4');
我可以将所有项目拆分为 ,
,但我如何“加入”以查找名称(例如 N8UXIAycxy3
--> district1
)?
我尝试以传统方式“加入”,但这行不通,因为 district_uid
无法访问这样的查询:
SELECT UNNEST(STRING_TO_ARRAY(co.attributevalues #>> '{"K54wAf6EX0s", "value"}', ',')) AS district_uid
FROM option o
JOIN district d on district_uid = d.uid;
我想要查询结果:district1,district2,district3,district4
。这是可能的还是我需要一个循环?
您需要将逗号分隔的字符串转换为数组,即 attributevalues->>'value'
:
select name
from option
cross join unnest(string_to_array(attributevalues->>'value', ',')) as district_uid
join district on uid = district_uid