在mysql查询中从字符串中提取字符串

时间:2012-07-25 06:44:22

标签: mysql

我有这个问题: -

 select col_str,
 getVal,another_str,resultVal_str from tablename

获得这样的结果:

 col_str                                        getVal   another_str              
'11,12,33,54,1,44'                              '12'    '9,5,4,8,7'               
'11,12,33,54,1,44,10,12,11,12,12'               '44'    '9,5,4,8,7,6,3,5,2,4,2'   
'11,12,33,54,1,44'                              '999'   '9,5,4,8,7,4'             
'11,12,33'                                      '0'     '9,5,4'                   
-----                                           ----      -----                   
-----                                           ----      -----                   
-----                                           ----      -----   

col_str,getVal,another_str来自表格,而resultVal_str列想要根据剩余的三列进行计算, resultVal_str的逻辑 -

查看第一个记录getVal,其值为12,col_str在位置编号为2的情况下为12,然后在another_str中查看位置编号2为5,那么resultVal_str为5等等。见下文:

col_str                                        getVal   another_str               resultVal_str
'11,12,33,54,1,44'                              '12'    '9,5,4,8,7'                  5
'11,12,33,54,1,44,10,12,11,12,12'               '44'    '9,5,4,8,7,6,3,5,2,4,2'      6
'11,12,33,54,1,44'                              '999'   '9,5,4,8,7,4'                0
'11,12,33'                                      '0'     '9,5,4'                      0
-----                                           ----      -----                     ---
-----                                           ----      -----                     ---
-----                                           ----      -----                     ---

如何添加下一栏resultVal_str并获得上述结果?

1 个答案:

答案 0 :(得分:0)

首先,你需要使用getVal函数在col_str中找到FIND_IN_SET的位置。

获得职位后,您可以使用resultVal函数在another_str中的同一位置找到SUBSTRING_INDEX

SELECT SUBSTRING_INDEX(SUBSTRING_INDEX(another_str, 
                       ",", (FIND_IN_SET(getVal, col_str))), 
                       ",", - 1) AS resultVal_str
FROM tablename;

试验:

SET @getVal = '12', @col_str = '11,12,33,54,1,44', @another_str = '9,5,4,8,7';

SELECT SUBSTRING_INDEX(SUBSTRING_INDEX(@another_str, ",", (FIND_IN_SET(@getVal, @col_str))), ",", - 1) AS resultVal_str;