我想确定文件夹的所有权。因此,每个文件夹都有一个常量命名约定,该约定存储在表OWNER(ident_string)中。 使用ident_string我想确定owner_id并将其写入(更新)到表FOLDER(owner_id)。
我在Postgresql中有以下表格:
create table owner(
owner_id serial PRIMARY KEY,
owner_name varchar(100),
ident_string varchar(100));
create table folder(
folder_id serial PRIMARY KEY,
folder_name varchar(80),
folder_path varchar(800),
owner_id integer references owner(owner_id));
insert into owner (owner_name, ident_string) values ('Jonny English','b-jonny');
insert into owner (owner_name, ident_string) values ('Hanna Babara','b-hanna');
insert into owner (owner_name, ident_string) values ('Mary Marmelade','b-mary');
insert into folder (folder_name,folder_path) values ('b-jonny-20130101','/archive/backup/b-jonny-20130101');
insert into folder (folder_name,folder_path) values ('b-jonny-20130103','/archive/backup/b-jonny-20130103');
insert into folder (folder_name,folder_path) values ('b-hanna-20140101','/archive/backup/b-jonny-20140101');
insert into folder (folder_name,folder_path) values ('b-mary-20120303','/archive/backup/b-mary-20120303');
我认为这样做的唯一可能性是通过PL / pgSQL:
有人可以帮帮我吗?
答案 0 :(得分:2)
也许类似于以下内容?
update folder set folder.owner_id = owner.owner_id from folder join owner on folder_name like owner.ident_string + '%'
(就像sql中正则表达式的方法一样)
答案 1 :(得分:1)
试试这个:
update folder as f
set owner_id = o.owner_id
from owner as o
where o.ident_string = left(f.folder_name,length(o.ident_string));
-g
答案 2 :(得分:1)
您可以用一句话创建表folder
:
insert into folder (folder_name,folder_path,owner_id)
with tmp (folder_name,folder_path) as
(
select 'b-jonny-20130101','/archive/backup/b-jonny-20130101' union all
select 'b-jonny-20130103','/archive/backup/b-jonny-20130103' union all
select 'b-hanna-20140101','/archive/backup/b-jonny-20140101' union all
select 'b-mary-20120303','/archive/backup/b-mary-20120303'
)
select folder_name,folder_path,o.owner_id
from tmp
join owner o
on tmp.folder_name ~ o.ident_string;
select * from owner;
使用正则表达式(〜),它更强大。