mysql USES group_concat of to merge multiple rows of data into one row

  • 2020-06-23 02:06:05
  • OfStack

Assume that the two tables a,b and b are associated with the a table by the field id, and that the a table has a one-to-many relationship with the b table. Hypothesis name b exists in the table 1 field, now need to query a records in the table, at the same time get stored in b name information in a table, according to the conventional query, b how many records in the table, will show how many rows, if you need to show only a table record number of lines, you will need to carry more query name field rows merged, can be implemented by the program, but also can directly in complete sql floor.

Methods:

Using the group_concat() method, the parameter is the field to be merged, the delimiter of the merged field is a comma by default, and can be specified by the parameter separator, this method is often used with group by 1.

Example:


select a.*,group_concat(b.name separator '-') as name from a left join b on a.id=b.id group by a.id;

Related articles: