2012-07-25 73 views
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,则看到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

+0

我可以在这里看到例如你给了,那没有。 col_str和another_str中的项目不同。如果在col_str中getVal的值发生超出another_str的范围,您会发现什么?此外,如果getVal不存在于col_str中,你期望什么?您的数据示例中的第4行。 – Shubhansh 2012-07-25 07:20:26

+0

然后它应该在结果表中生成0,参见上面的结果表的'resultVal_str'列。 – Bajrang 2012-07-25 10:33:23

回答

0

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

一旦你的位置,你可以找到使用SUBSTRING_INDEX功能another_strresultVal从相同的位置:

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; 
+0

但我如何在上述查询中实现? – Bajrang 2012-07-25 07:16:34