How to use Mysql's GROUP_CONCAT() function_PHP tutorial
Jul 21, 2016 pm 03:53 PM
Syntax:
GROUP_CONCAT([DISTINCT] expr [,expr ...][ORDER BY {unsigned_integer | col_name | expr}[ASC | DESC] [,col_name ...]][SEPARATOR str_val])
Let’s demonstrate this function. First, create a student course selection table student_courses and fill in some test data.
SQL code
CREATE TABLE student_courses (
student_id INT UNSIGNED NOT NULL,
courses_id INT UNSIGNED NOT NULL,
KEY(student_id)
);
INSERT INTO student_courses VALUES (1, 1), (1, 2), (2, 3), ( 2, 4), (2, 5);
To find the course selected by student ID 2, use the following SQL:
SQL code
mysql> SELECT student_id, courses_id FROM student_courses WHERE student_id=2;
+- -----------+----------------+
| student_id | courses_id |
+------------+ ------------+
+--------- ---+----------------+
3 rows IN SET (0.00 sec)
The output result has 3 records, indicating the student ID Three courses, 3, 4, and 5, were selected for student 2.
PHP code
Copy the code
If you use the GROUP_CONCAT() function and the GROUP BY statement, it is very simple, as shown below:
SQL code
Copy code
This way the processing in php is simple:
PHP code
Copy code
The code is as follows:
$row = $pdo-> query("SELECT student_id, GROUP_CONCAT(courses_id) AS courses FROM student_courses WHERE student_id=2 GROUP BY student_id");
separator can also be customized. The default is "," as the separator. If you want to change it to "|||", use SEPARATOR to specify it, for example:
SQL code
SELECT student_id, GROUP_CONCAT(courses_id SEPARATOR '|||') AS courses FROM student_courses WHERE student_id=2 GROUP BY student_id;
In addition, you can also sort the values of this group and then concatenate them into strings, for example, sort by courses_id in descending order:
SQL code
SELECT student_id, GROUP_CONCAT(courses_id ORDER BY courses_id DESC) AS courses FROM student_courses WHERE student_id=2 GROUP BY student_id;

Hot Article

Hot tools Tags

Hot Article

Hot Article Tags

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

PHP's big data structure processing skills

How to optimize MySQL query performance in PHP?

How to use MySQL backup and restore in PHP?

What are the application scenarios of Java enumeration types in databases?

How to insert data into a MySQL table using PHP?

How to fix mysql_native_password not loaded errors on MySQL 8.4

How to use MySQL stored procedures in PHP?

Complete collection of excel function formulas
