Mysql uses Group_concat to merge multiple data display methods _mysql

Source: Internet
Author: User

This article describes the MySQL use of Group_concat merged with a number of data display methods, to share with you for your reference. The implementation methods are as follows:

Suppose there is such a requirement:
1: Class table:
ID class_name
2: Student Table:
ID Name class_id

If we were to check all the classes and the students in each class, you would have thought of that:

Copy Code code as follows:
SELECT
banji.*, User.Name
From ' Banji '
Left JOIN user
On Banji.id=user. ' Class '
where banji.id=2

So the number of results we get is the same as the number of students, and I want to get a piece of data, and this data contains all the students, you can write:

Copy Code code as follows:
SELECT
banji.*, Group_concat (user.name) as names
From ' Banji '
Left JOIN user
On Banji.id=user. ' Class '
where banji.id=2

This results in a single result, and the result contains all the student name,

Id Class_name Names
2 Two Lisi,zhaoliu,liu, Waiter, Xiaoming, Xiao Zhang

You can also customize the separator:

Copy Code code 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

The results obtained:

Id Class_name Names
2 Two lisi|zhaoliu|liu| small two |xiaoming| Xiao Zhang

Second, we hope that this article on the MySQL database program design help.

Related Article

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.