Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What are the SQL skills of row-column transformation in MySQL

2025-02-24 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Database >

Share

Shulou(Shulou.com)05/31 Report--

This article is about SQL techniques for column conversion in MySQL. Xiaobian thinks it is quite practical, so share it with everyone for reference. Let's follow Xiaobian and have a look.

Common scenes of row and column transition

Because many business tables use design patterns that violate the first normal form for historical or performance reasons. That is, multiple attribute values are stored in the same column (see the following table for specific structure). In this pattern, applications often need to divide the column by separators and get the result of column rotation.

Table data:

ID

Value

1

tiny,small,big

2

small,medium

3

tiny,big

Expect results:

ID

Value

1

tiny

1

small

1

big

2

small

2

medium

3

tiny

3

big

specific methods

Let's start with a concrete example:

#Prepare sample data

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');

#Self-increasing table for column conversion cycle

create table incre_table (AutoIncreID int);

insert into incre_table values (1);

insert into incre_table values (2);

insert into incre_table values (3);

#SQL for row and column conversion

select a.ID,substring_index(substring_index(a.mSize,',',b.AutoIncreID),',',-1)

from

tbl_name a

join

incre_table b

on b.AutoIncreID

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Database

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report