在mysql中选择字符串的一部分 [英] Select part of a string in mysql
问题描述
我在这样的一列中有一个 string
I have a string
in one column like this
India_Project1_BA_Protex_123
Japan_ProQ_CXR_Tbxc_3456
我需要在mySQL
推荐答案
提取字符串的某些部分有两个函数,它们是 SUBSTRING
&SPLITSTRING
但 SUBSTRING
在这种情况下不能使用,并且 SPLITSTRING
在 MySql
中不存在.所以你必须编写自己的函数:
There are two functions for extracting some part of string, they are SUBSTRING
& SPLITSTRING
but SUBSTRING
can not be used in this case and SPLITSTRING
is not present in MySql
. So you have to write your own function:
MySQL 不包含拆分字符串的函数.但是,创建自己的函数非常容易.
创建函数语法
用户定义的函数是一种用新的扩展 MySQL 的方法功能类似于本机 MySQL 函数.
A user-defined function is a way to extend MySQL with a new function that works like a native MySQL function.
CREATE [AGGREGATE] FUNCTION function_name
RETURNS {STRING|INTEGER|REAL|DECIMAL}
要创建一个函数,你必须有 INSERT 权限数据库.
To create a function, you must have the INSERT privilege for the database.
分割字符串
以下示例函数接受 3 个参数,执行一个使用SQL函数操作,并返回结果.
The following example function takes 3 parameters, performs an operation using an SQL function, and returns the result.
功能
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, '');
使用
SELECT SPLIT_STR(string, delimiter, position)
示例
SELECT SPLIT_STR('India_Project1_BA_Protex_123', '_', 2) as second;
SELECT SPLIT_STR('India_Project1_BA_Protex_123', '_', 3) as third;
+------------++-------+
| second || third |
+------------++-------+
| Project1 || BA |
+------------++-------+
| ProQ || CXR |
+------------++-------+
现在您可以连接两个结果.以获得最终结果.
Now you can concatenate the two results. to get your final result.
完整教程在这里:http://blog.fedecarg.com/2009/02/22/mysql-split-string-function/
希望这会有所帮助.
这篇关于在mysql中选择字符串的一部分的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!