Split Varchar into Character in MySQL

前提是你 提交于 2019-12-10 22:00:00

问题


I have a varchar field with length 6. I want to split into single characters in MySQL. Currently I have tried with following script:

col = '123456';
{
select SUBSTRING(col,1, 1),
SUBSTRING(col, 2,1),
SUBSTRING(col, 3,1),
SUBSTRING(col, 4,1),
SUBSTRING(col, 5,1),
SUBSTRING(col, 6,1)
from tbl_table
}

The above script works but is there any other solution for this.

Thank You.


回答1:


There is no string split function in MySQL. so you have to create your own function. Use below link.This will help you

Split delimited strings

The following example function takes 3 parameters, performs an operation using an SQL function, and returns the result.

Function

CREATE FUNCTION SPLIT_STR(
  x VARCHAR(255),
  delim VARCHAR(12),
  pos INT
)
RETURNS VARCHAR(255)
RETURN REPLACE(SUBSTRING(SUBSTRING_INDEX(x, delim, pos),
       LENGTH(SUBSTRING_INDEX(x, delim, pos -1)) + 1),
       delim, '');

Usage

SELECT SPLIT_STR(string, delimiter, position)

Example

SELECT SPLIT_STR('a|bb|ccc|dd', '|', 3) as third;

+-------+
| third |
+-------+
| ccc   |
+-------+

Credits:http://blog.fedecarg.com/2009/02/22/mysql-split-string-function/




回答2:


Another solution would be use whatever (unknown) scripting language you are using to do the split. Otherwise, if it works, don't fix it.

To add some actual value to this answer, I will add that it would be a good practice to meaningfully name the columns:

col = '123456';
{
select SUBSTRING(col,1, 1) AS value1,
SUBSTRING(col, 2,1) AS value2,
SUBSTRING(col, 3,1) AS value3,
SUBSTRING(col, 4,1) AS value4,
SUBSTRING(col, 5,1) AS value5,
SUBSTRING(col, 6,1) AS value6
from tbl_table
}

Also, if you find yourself doing this, it means you are not properly using a RDBMS and each of those should be in a separate field.



来源:https://stackoverflow.com/questions/20971794/split-varchar-into-character-in-mysql

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!