insert into tpems.sp_questions_bank (id, title, option_a, option_b, option_c, option_d, option_e, answer1, answer2, parse, qtpye, diff, md5, subjectId, gradeId, knowledges, area, year, paperTpye, source, fromSite, isSub, isNormal, isKonw, tiid, Similarity, isunique, md52, s_type, s_qid, s_pid, s_user_id, s_user_name, s_option_number, s_status, s_create_time, s_last_update_time, s_is_exercise, s_select_number ) SELECT null, t.title, IF(t.opi >= 1, t.option_a, '') a, IF(t.opi >= 2, t.option_b, '') b, IF(t.opi >= 3, t.option_c, '') c, IF(t.opi >= 4, t.option_d, '') d, IF(t.opi >= 5, t.option_e, '') e, t.answer, null, t.description, t.type, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, 0, t.id, t.pid, t.user_id, t.user_name, t.option_number, t.status, t.create_time, t.last_update_time, t.is_exercise, t.select_number FROM (SELECT sp.id, sp.user_id, sp.type, sp.title, sp.user_name, sp.option_number, sp.answer, sp.description, sp.status, sp.create_time, sp.last_update_time, sp.is_exercise, sp.pid, sp.select_number, (LENGTH(sp.option) - LENGTH(REPLACE(sp.option, '^^', ''))) / 2 + 1 AS opi, if(sp.type in(4,5,6),sp.option,SUBSTRING_INDEX(SUBSTRING_INDEX(sp.option, '^^', 1), '^^', - 1)) AS option_a, if(sp.type in(4,5,6),'',SUBSTRING_INDEX(SUBSTRING_INDEX(sp.option, '^^', 2), '^^', - 1)) as option_b, if(sp.type in(4,5,6),'',SUBSTRING_INDEX(SUBSTRING_INDEX(sp.option, '^^', 3), '^^', - 1)) as option_c, if(sp.type in(4,5,6),'',SUBSTRING_INDEX(SUBSTRING_INDEX(sp.option, '^^', 4), '^^', - 1)) as option_d, if(sp.type in(4,5,6),'',SUBSTRING_INDEX(SUBSTRING_INDEX(sp.option, '^^', 5), '^^', - 1)) as option_e FROM tpems.sp_question sp) t;
首先描述下個人sql的工做場景,有一列數據是用分隔符「^^」進行分隔的,一個字段裏的值,而後須要把字段拆開,而後放到不一樣的option裏面去, option有5個,而後字段裏的分隔符的數目也是不固定的。 這裏我是肯定了一下最大的上限值,最多隻能寫5個,而後這樣就簡單了。sql
(LENGTH(sp.option) - LENGTH(REPLACE(sp.option, '^^', ''))) / 2 + 1 AS opi
肯定了分隔符能夠分出的列數。函數
而後判斷選項的個數code
IF(t.opi >= 1, t.option_a, '') a, IF(t.opi >= 2, t.option_b, '') b, IF(t.opi >= 3, t.option_c, '') c, IF(t.opi >= 4, t.option_d, '') d, IF(t.opi >= 5, t.option_e, '') e,
這裏解釋下if函數,if(表達式,a,b) 表達式若是爲真則返回a,不然返回b 因此這裏的判斷就是,若是隻能分出兩個option則,3,4,5的值都是空 ,就成功的將一列值擴充到多列orm