我有这个问题: -
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 :(得分: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;