MySql adopts GROUP_CONCAT to merge multiple data display methods _ MySQL

Source: Internet
Author: User
This article describes how MySql uses GROUP_CONCAT to merge multiple data display methods. it is a common practical technique in MySQL database programming, for more information about how to use GROUP_CONCAT to merge multiple data entries in MySql, see the following example. The specific implementation method is as follows:

Assume that you have the following requirement:
1: Class table:
Id class_name
2: Student table:
Id name class_id

If we want to check all the classes and the students in each class, you will think of the following method:

The code is as follows:

SELECT
Banji. *, user. name
FROM 'banji'
Left join user
On banji. id = user. 'class'
Where banji. id = 2


In this way, the number of students is the same as the number of students, and I want to get a piece of data, which also contains all the students. you can write it like this:

The code is as follows:

SELECT
Banji. *, GROUP_CONCAT (user. name) as names
FROM 'banji'
Left join user
On banji. id = user. 'class'
Where banji. id = 2


In this way, only one result is returned, and the result contains the names of all students,

Id Class_name Names
2 II Lisi, zhaoliu, liu, Xiao'er, xiaoming, Xiaozhang

You can also customize separators:

The code is as follows:

SELECT
Banji. *, GROUP_CONCAT (user. name SEPARATOR "|") as names
FROM 'banji'
Left join user
On banji. id = user. 'class'
Where banji. id = 2


Result:

Id Class_name Names
2 II Lisi | zhaoliu | liu | | xiaoming | Xiao Zhang

II. I hope this article will help you design your MySQL database program.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.