Combine multiple rows of data into one row of data in mysql GROUP_CONCAT()

A field may correspond to multiple pieces of data. Use mysql to merge multiple rows of data into one row of data

For example: an activity id (activeId) corresponds to multiple module names (modelName), according to the general SQL statement:

1 SELECT am.activeId,m.modelName 
2 FROM activemodel am 
3 JOIN  model m 
4 ON am.modelId = m.modelId 
5 ORDER BY am.activeId

The query list is shown in Figure 1: 

      figure 1

The modified sql statement is shown in Figure 2 after query:

1 SELECT am.activeId,GROUP_CONCAT(m.modelName SEPARATOR ',') modelName
2 FROM activemodel am 
3 JOIN model m 
4 ON am.modelId=m.modelId
5 WHERE m.valid=1
6 GROUP BY am.activeId

Note:

1. The value in GROUP_CONCAT () is the field name of the data you want to merge;

 The SEPARATOR function is used to separate the data to be merged;

 '' Is which symbol you want to use to separate;

2. The GROUP BY statement must be used for group management, otherwise all the data will be merged into one record, as shown in Figure 3.

            figure 2

 

                    image 3

Guess you like

Origin blog.csdn.net/zhaofuqiangmycomm/article/details/113592373