2015-05-28 31 views
0

删除角色我都行, 例如:1,2,3,5,9,7 - >不是在(3,7) (这个字需要删除 - >结果选择1,2,5,9 如何做到这一点如何从列表

例如? :

drop table test.table_4; 
create table test.table_4 (
    id integer, 
    list_id text 
); 
insert into test.table_4 values(1,'1,2,3,5,9,7'); 
insert into test.table_4 values(2,'1,2,3,5'); 
insert into test.table_4 values(3,'7,9'); 
insert into test.table_4 values(5,'1,2'); 
insert into test.table_4 values(9,'1'); 
insert into test.table_4 values(7,'5,7,9'); 

查询:

select list_id from test.table_4 where id not in (3,7) --return 4 row 

    id list_id 
1. 1  '1,2,3,5,9,7' 
2. 2  '1,2,3,5' 
3. 5  '1,2' 
4. 9  '1' 

如何在第1行删除3,7和2

id 
1. 1  '1,2,5,9' 
2. 2  '1,2,5' 
3. 5  '1,2' 
4. 9  '1' 
+0

你能建立一个sqlfiddle HTTP://sqlfiddle.com/ –

+1

你问如何删除字符串中的任何'7'?还是你问如何删除最后一个字符?请澄清。 – Linger

+0

@Linger或第一个字符不是为了^ ^。如此多的可能性。 – ShellFish

回答

1

下应在字符串的开始处理3或7,在字符串,或在中间的任何位置结束。这也确保了31 3和17 7不被替换:

select 
    list_id, 
    regexp_replace(list_id, '(^[37],|,[37](,)|,[37]$)', '\2', 'g') 
from test.table_4 
where id not in (3,7) 

说明:
^[37],相匹配的3或7然后在字符串的开头逗号。这应该被替换为无。
,[37](,)相匹配的,3个,或,如图7所示,在字符串的中间。这需要用一个逗号替换,逗号由括号括起来。
[37]$相匹配的3或7在字符串的前面端通过逗号。这应该被替换为无。

\2是用来替换的字符串 - 这是,上面第二种情况下,空的情况下,1和3

+0

TobyLL,谢谢!!! – Testudinate

0

您可以使用以下语句更新所有记录。在下面的例子中,第一条语句将删除找到的所有,7。然后执行下一条语句,查找字符串前面的7

UPDATE test.table_4 SET list_id = REPLACE(list_id, ',7', '') 
UPDATE test.table_4 SET list_id = REPLACE(list_id, '7', '') 

如果您也想删除的3所有出现然后执行以下语句:

UPDATE test.table_4 SET list_id = REPLACE(list_id, ',3', '') 
UPDATE test.table_4 SET list_id = REPLACE(list_id, '3', '') 

然而,这是一个糟糕的设计,你需要agianst搜索存储值,工作着,等字符串。

+0

数据不需要update.query显示没有id 3和7的字符串。 – Testudinate

0

您可以使用regexp_replace获得预期的输出:

select id, regexp_replace(list_id,'3,|,7', '','g') 
from table_4 
where id not in (3,7) 

输出:

id regexp_replace 
1 1,2,5,9 
2 1,2,5 
5 1,2 
9 1 

这里是SQL Fiddle