The Group_concat function in MySQL displays multiple data as a single piece of data

Source: Internet
Author: User

There is such a demand
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:

The code is as follows Copy Code
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:

The code is as follows Copy Code
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

22 Lisi,zhaoliu,liu, Waiter, Xiaoming, Xiao Zhang

You can also customize the separator:

  code is as follows copy code
select
banji.*, Group_concat (user.name SEPARATOR "|") as names
from ' Banji '
Left join user
on Banji.id=user. ' Class '
where banji.id=2
Results:
id  class_name  names
2  two   lisi|zhaoliu|liu| small two |xiaoming| Small Zhang

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.