根据分隔符" |"将一列拆分为三列。

时间:2017-04-17 01:21:28

标签: sql substring

我有一张桌子

id  methods
1   a|b|c
2   e|f|g

如何将表格更改为

id method1 method2 method3
1    a       b       c
2    e       f       g

1 个答案:

答案 0 :(得分:1)

不确定您使用的是哪个RDBMS但是我在Sql Server,MySql和SQLite中使用它。这假设只有三个项目需要从字符串中拆分

重申@Joel Coehoorn提到的内容。当给出大量数据时,这可能非常慢。最好更改表的模式,并在将数据插入表

之前拆分数据

SQL Server版本

select  t.id, t.methods,
 SUBSTRING(t.methods, 1, CHARINDEX('|', t.methods)-1) as method1,
 SUBSTRING(t.methods, CHARINDEX('|', t.methods)+1, CHARINDEX('|', t.methods, CHARINDEX('|', t.methods)+1)-CHARINDEX('|', t.methods)-1) as method2,
 SUBSTRING(t.methods, CHARINDEX('|', t.methods, CHARINDEX('|', t.methods)+1)+1,len(t.methods)) as method3
 from TestTable t

MySql版本

select  t.id, t.methods,
 SUBSTRING(t.methods, 1, LOCATE('|', t.methods)-1) as method1,
 SUBSTRING(t.methods, LOCATE('|', t.methods)+1, LOCATE('|', t.methods, LOCATE('|', t.methods)+1)-LOCATE('|', t.methods)-1) as method2,
 SUBSTRING(t.methods, LOCATE('|', t.methods, LOCATE('|', t.methods)+1)+1) as method3
 from TestTable t

<强> SQLite的

 select 
 SUBSTR(t.methods, 1, INSTR(t.methods, '|')-1) as method1,
 SUBSTR(t.methods, INSTR(t.methods, '|')+1, INSTR(SUBSTR(t.methods, INSTR(t.methods, '|')+1), '|')-1) as method2,
 SUBSTR(t.methods, INSTR(SUBSTR(t.methods, INSTR(t.methods, '|')+1), '|')+ INSTR(t.methods, '|')+1) as method3
 from TestTable t