mysql用逗號分割字串
阿新 • • 發佈:2018-12-30
這是我的表結構,需要分割的就是KEY的值
採用的是mysql的substring_index函式:
-
select a.ID,a.DOCTORID, substring_index(substring_index(a.`KEY`,',',b.help_topic_id+1),',',-1) as key1 from doctorarea a join mysql.help_topic b on b.help_topic_id < (length(a.`KEY`) - length(replace(a.`KEY`,',',''))+1)
- 我在我本地mysql資料庫執行沒有任何問題,但是放在專案中,呼叫遠端資料庫,結果永遠是空。原因是sql裡面用了mysql一個自帶的臨時表:help_topic,我本地裡面是該表是有值的,但是發現遠端資料庫中該表是沒有值,我把我表裡面的資料,複製到遠端資料庫的 help_topic中再次執行,發現可以了。
- help_topic:一般為系統表,輕易不要修改,那麼可以自己新建一個表,help_index,裡面就一個欄位help_index_id,只要保證這個表裡面有較多資料,就可以了:那麼上面程式碼可以換成下面這個:
select a.ID,a.DOCTORID, substring_index(substring_index(a.`KEY`,',',b.help_topic_id+1),',',-1) as key1 from doctorarea a join help_index b on b.help_index_id < (length(a.`KEY`) - length(replace(a.`KEY`,',',''))+1)