I used MySQL to know that she had a good function of group_concat function, which is very convenient.
Click (here) to collapse or open
- SELECT
- *
- From
- Group_test;
- SELECT
- Id
- Group_concat (sub_id)
- From
- ' Group_test '
- GROUP by
- Id
Now the demand is that there is a similar result set in Figure two above, the need to convert the column two split rows record
We know that if it's a single record, it's easy to implement Substring_index
Click (here) to collapse or open
- Select Id,substring_index (sub_id, ', ', 1) from Group_test where id=3
- UNION
- Select Id,substring_index (Substring_index (sub_id, ', ', 2), ', ', -1) from Group_test where id=3
- UNION
- Select Id,substring_index (Substring_index (sub_id, ', ', 3), ', ', -1) from Group_test where id=3
But what if it's n? You can also use Substring_index to do this, except that you need a configuration table that is implemented via cross join, first look at the Intersect join
Click (here) to collapse or open
- SELECT
- *
- From
- (Select 1 UNION select 2) t1
- Cross JOIN (select 3 UNION select 4) t2
The following is the implementation of our requirements through cross joins and Substring_index, first building a configuration table
Click (here) to collapse or open
- create table digits (Digit int (1));
- insert into digits
- VALUES
- (0),
- (1),
- (2),
- (3),
- (4),
- (5),
- (6),
- (7),
- (8),
- (9);
- create table sequence (Seq int (3));
- insert into sequence (
- select
- d1.digit + d2.digit * 10
- From
- digits D1
- cross JOIN digits D2
- );
And then
Click (here) to collapse or open
- SELECT
- Id
- Substring_index (
- Substring_index (sub_id, ', ', seq),
- ', ',-1
- ) sub_id,
- Seq
- From
- Sequence
- Cross JOIN Group_test
- WHERE
- Seq between 1
- and (
- SELECT
- 1 + Length (sub_id)-Length (REPLACE (sub_id, ', ', '))
- )
- ORDER by
- Id
- sub_id;
Original sticker: http://blog.chinaunix.net/uid-411974-id-3990697.html
(go) MySQL group_concat reverse application implementation (MySQL row)