Home > Database > Mysql Tutorial > How to Concatenate Strings in MySQL Using GROUP BY?

How to Concatenate Strings in MySQL Using GROUP BY?

Barbara Streisand
Release: 2025-01-21 20:46:10
Original
266 people have browsed it

How to Concatenate Strings in MySQL Using GROUP BY?

Using GROUP BY connection string in MySQL

In database management systems, it is often necessary to merge multiple strings into a single string. In MySQL, you can use the GROUP BY function to achieve this functionality.

The syntax for MySQL string concatenation is as follows:

<code class="language-sql">SELECT id, GROUP_CONCAT(name SEPARATOR ' ') FROM table GROUP BY id;</code>
Copy after login

This query will group the rows by the id column and concatenate the values ​​in the name column using the specified separator (space in this case).

Example

Consider the following form:

foo_id foo_name
1 A
1 B
2 C

To concatenate the foo_id values ​​for each foo_name you can execute the following query:

<code class="language-sql">SELECT foo_id, GROUP_CONCAT(foo_name SEPARATOR ' ') FROM foo GROUP BY foo_id;</code>
Copy after login

This query will return the following results:

foo_id foo_name
1 A B
2 C

As you can see, each foo_id value of foo_name has been concatenated into a single string.

Additional information

  • GROUP_CONCAT Functions can concatenate any data type, not just strings.
  • You can specify multiple columns in the GROUP BY clause.
  • You can also specify the order in which values ​​are concatenated.

For more information about the GROUP_CONCAT function, see the MySQL documentation: https://www.php.cn/link/18fc3b6cc1e55ccea877c161e2e9ba27

The above is the detailed content of How to Concatenate Strings in MySQL Using GROUP BY?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template