MySQL逗號分割欄位的列轉行

來源:互聯網
上載者:User

標籤:使用   too   設計   help   轉行   gpo   incr   技術分享   comm   

前言:

由於很多業務表因為曆史原因或者效能原因,都使用了違反第一範式的設計模式。即同一個列中儲存了多個屬性值(具體結構見下表)。

這種模式下,應用常常需要將這個列依據分隔字元進行分割,並得到列轉行的結果。

 

表資料:

ID  Value
1 tiny,small,big
2 small,medium
3 tiny,big

期望得到結果:

ID Value
1 tiny
1 small
1 big
2 small
2 medium
3 tiny
3 big

 

總結:

這種方法的缺點在於,我們需要一個擁有連續數列的獨立表(這裡是incre_table)。並且連續數列的最大值一定要大於符合分割的值的個數。

例如有一行的mSize 有100個逗號分割的值,那麼我們的incre_table 就需要有至少100個連續行。

當然,mysql內部也有現成的連續數列表可用。如mysql.help_topic: help_topic_id 共有504個數值,一般能滿足於大部分需求了。

改寫後如下:

#需要處理的表create table tbl_name (ID int ,mSize varchar(100));insert into tbl_name values (1,‘tiny,small,big‘);insert into tbl_name values (2,‘small,medium‘);insert into tbl_name values (3,‘tiny,big‘);#SQLselect a.ID,substring_index(substring_index(a.mSize,‘,‘,b.help_topic_id+1),‘,‘,-1) from tbl_name ajoinmysql.help_topic bon b.help_topic_id < (length(a.mSize) - length(replace(a.mSize,‘,‘,‘‘))+1)order by a.ID;

MySQL逗號分割欄位的列轉行

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.