我正在从一个不同的模式导入;我导入的字段在varchar中有一个逗号分隔的类别列表(例如,类别:"foo,bar,baz,boo")
id name categories
1 abc foo,bar
2 def baz,boo
原生模式有一个类别名称表(例如,id1name:“foo”,id2name:“bar”,...)以及将项目的id链接到类别的id的表item_to_category。
如何在SQL,Postgres中实现这一点,具体来说,采取了什么步骤--分解它。SQL是解决这一问题的合适工具吗?还是有更好的策略?
发布于 2021-11-14 22:02:01
我解决这个问题的方法是创建一个函数,迭代所有记录,将字符串数组提取到一个varchar[]数组中,迭代该数组,然后输出到我的类别和索引表中。某个人,某个地方。
CREATE TABLE public.categories (
id SERIAL PRIMARY KEY NOT NULL,
parent Integer,
category Text NOT NULL UNIQUE
);
CREATE TABLE public.companies_categories (
id SERIAL PRIMARY KEY NOT NULL,
category_id Integer NOT NULL,
company_id Integer NOT NULL
);
create or replace function scan_categories()
returns setof categories as $$
declare
category_list varchar[];
category_text varchar;
category_id int;
company_id int;
BEGIN
FOR category_list, company_id IN SELECT categories, id FROM public.companies
LOOP
IF category_list IS NOT NULL
THEN
FOREACH category_text IN ARRAY category_list
LOOP
INSERT INTO public.categories(category) VALUES (category_text) ON CONFLICT DO NOTHING;
SELECT id FROM public.categories INTO category_id WHERE category LIKE category_text;
INSERT INTO companies_categories (category_id, company_id) VALUES (category_id, company_id);
END LOOP;
END IF;
END LOOP;
END
$$
https://stackoverflow.com/questions/69961199
复制相似问题