Home  >  Article  >  Database  >  How to merge rows in mysql

How to merge rows in mysql

coldplay.xixi
coldplay.xixiOriginal
2020-08-25 10:26:513507browse

Mysql method of merging rows: use the function [GROUP_CONCAT()], the code is [SELECT am.activeId,GROUP_CONCAT(m.modelName SEPARATOR ',') modelName].

How to merge rows in mysql

[Related learning recommendations: mysql learning]

Mysql merge row method:

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 The 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:

How to merge rows in mysql

##Figure 1


After modification sql statement, as 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.

GROUP_CONCAT()

The value in 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 data will be merged into one record, as shown in Figure 3

How to merge rows in mysqlFigure 2

How to merge rows in mysqlimage 3

The above is the detailed content of How to merge rows in mysql. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn