mysql單欄位包含多值列轉行問題
阿新 • • 發佈:2021-01-16
有些時候因為表設計問題,會存在多個值以逗號隔開存在一個欄位裡,例如:
這樣在一些特定的場合會造成查詢困難,我們需要把他列轉行,主要利用substring_index函式進行分割,以下列子藉助mysql自帶的表help_topic 的id加以輔助查詢,其中content_blog_article 和content_blog_note 為業務資料表:
SELECT * from ( ( -- 文章部落格 SELECT * from ( select a.id,substring_index(substring_index(a.tag,',',b.help_topic_id+1),',',-1) as tag, a.create_time as createTime from content_blog_article a join mysql.help_topic b on b.help_topic_id < (length(a.tag) - length(replace(a.tag,',',''))+1) ) as result where tag in (select tag from content_tag where type = "WHDK") ) UNION ( -- 相簿部落格 SELECT * from ( select a.id,substring_index(substring_index(a.tag,',',b.help_topic_id+1),',',-1) as tag, a.create_time as createTime from content_blog_note a join mysql.help_topic b on b.help_topic_id < (length(a.tag) - length(replace(a.tag,',',''))+1) ) as result where tag in (select tag from content_tag where type = "WHDK") ) ) as result order by createTime desc