1

我有这个查询: -

 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,然后查看位置编号 2another_str为 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并获得类似上面的结果?

4

1 回答 1

0

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

一旦你得到位置,你可以在使用函数的resultVal相同位置找到:another_strSUBSTRING_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;
于 2012-07-25T06:52:42.203 回答