删除PostgreSQL表字符串中的子字符串

时间:2013-08-23 10:26:15

标签: string attributes substring postgresql-9.2

我在PostgreSQL数据库中有表'A':

name     fullname
A         A,I,A
B         B,B,S,B
D         D,D,S,E,D
E         E,E,D,G,E
F         F,F,G,F
G         G,E,G,F,G,H,N,G

如何接收带有'correctname'(fullname)列的表'B',其中每行中没有来自'name'字段的匹配子字符串:

name  correctname
A      I
B      S
D      S,E
E      D,G
F      G
G      E,F,H,N

数据样本:

CREATE TABLE test(name TEXT, fullname TEXT);

INSERT INTO test(name, fullname) VALUES('A','A,I,A');
INSERT INTO test(name, fullname) VALUES('B','B,B,S,B');
INSERT INTO test(name, fullname) VALUES('D','D,D,S,E,D');
INSERT INTO test(name, fullname) VALUES('E','E,E,D,G,E');
INSERT INTO test(name, fullname) VALUES('F','F,F,G,F');
INSERT INTO test(name, fullname) VALUES('G','G,E,G,F,G,H,N,G');

谢谢!

1 个答案:

答案 0 :(得分:0)

Solution

SELECT 
name
,trim(
REGEXP_REPLACE(fullname,'(,|^)('||name||'(,|$))+',',','cg')
,',')
FROM data;

SELECT REPLACE(REPLACE(fullname, name||',', ''), ','||name, '') FROM test;