1. 程式人生 > 其它 >mysql單欄位包含多值列轉行問題

mysql單欄位包含多值列轉行問題

技術標籤:mysqlmysql

有些時候因為表設計問題,會存在多個值以逗號隔開存在一個欄位裡,例如:

在這裡插入圖片描述

這樣在一些特定的場合會造成查詢困難,我們需要把他列轉行,主要利用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

最終效果,把id為“03dfe53867b91b6bef83b7f2bdb95e4a”的記錄的tag欄位以逗號隔開的值轉成列了:

在這裡插入圖片描述