数据库中有业务表t1和字典表dictionary
t1表: dictionary表:
SQL 代码如下所示:
方法一:
SELECT col,a[1] a1,a[2] a2,a[3] a3 FROM ( SELECT regexp_split_to_array( col, ',' ), col FROM t1 ) AS dt (a)
效果:
方法二:
SELECT col, SPLIT_PART( col, ',', 1 ) a1, SPLIT_PART( col, ',', 2 ) a2, SPLIT_PART( col, ',', 3 ) a3 FROM t1
效果:
ALTER TABLE t1 ADD COLUMN col1 VARCHAR(30); ALTER TABLE t1 ADD COLUMN col2 VARCHAR(30); ALTER TABLE t1 ADD COLUMN col3 VARCHAR(30);
UPDATE t1 SET col1 = SPLIT_PART( col, ',', 1 ), col2 = SPLIT_PART( col, ',', 2 ), col3 = SPLIT_PART( col, ',', 3 );
效果:
SQL 代码如下所示:
SELECT col, (SELECT name from dictionary WHERE id=a[1]) a1, (SELECT name from dictionary WHERE id=a[2]) a2, (SELECT name from dictionary WHERE id=a[3]) a3 FROM ( SELECT regexp_split_to_array( col, ',' ), col FROM t1 ) AS dt (a)
效果:
SQL 代码如下所示:
SELECT col,CONCAT_WS(',',a1,a2,a3) as names FROM ( SELECT col, (SELECT name from dictionary WHERE id=a[1]) a1, (SELECT name from dictionary WHERE id=a[2]) a2, (SELECT name from dictionary WHERE id=a[3]) a3 FROM ( SELECT regexp_split_to_array( col, ',' ), col FROM t1 ) AS dt (a) ) as temp
效果:
我们可能会遇到按分隔符拆成多行或者多列的情况,以及复制的业务需求,只需视情况调整sql语句,或者编写存储过程。
对于列col的值,按分隔符拆分为多列数据时,不知道需要拆分成几列,可以先用以下sql查询出列数。
SELECT max(array_length(regexp_split_to_array(col,','),1)) FROM t1;