1. 程式人生 > >mysql擷取欄位並插入到新的欄位中

mysql擷取欄位並插入到新的欄位中

例如:在產品表product表中欄位content值為["10"],然後在產品表中新建一個欄位product_id,提出欄位content的值10,如何實現呢?

解:

update (select id,substring(content,3,instr(content,"\"]")-3) as product_id FROM `product`) b,product a set a.product_id = b.product_id WHERE a.id = b.id 

解析:

instr(欄位名, 字串)——這個函式返回字串在某一個欄位的內容中的位置, 沒有找到字串返回0,否則返回位置(從1開始)

substring(被擷取欄位,從第幾位開始擷取,擷取長度)

拓展:

left(被擷取的欄位,擷取長度)——從左開始擷取字串

right(被擷取的欄位,擷取長度)——從右開始擷取字串

substring_index(被擷取欄位,關鍵字,關鍵字出現的次數)——按關鍵字擷取字串 

(注:如果關鍵字出現的次數是負數 如-2 則是從後倒數,到字串結束)