GROUP_CONCAT()是MySQL数据库提供的一个函数,通常跟GROUP BY一起用,具体可参考MySQL官方文挡:http://dev.mysql.com/doc/refman/5.0/en/group-by-functions.html#function_group-concat。语法: GROUP_CONCAT([DISTINCT]?expr?[,expr ...]?[ORDER?BY?{unsigne
GROUP_CONCAT()是MySQL数据库提供的一个函数,通常跟GROUP BY一起用,具体可参考MySQL官方文挡:http://dev.mysql.com/doc/refman/5.0/en/group-by-functions.html#function_group-concat。 语法:GROUP_CONCAT([DISTINCT]?expr?[,expr ...]?[ORDER?BY?{unsigned_integer | col_name | expr}?[ASC?|DESC]?[,col_name ...]]?[SEPARATOR str_val]) 1.例如: SELECT?student_id, GROUP_CONCAT(courses_id)?AS courses?FROM?student_courses?WHEREstudent_id=2?GROUP?BY?student_id;? +------------+---------+? | student_id | courses |? +------------+---------+? |?2? |?3,4,5?| +------------+---------+? 这 就不需要用php循环了 $row?=?$pdo->query("SELECT student_id, GROUP_CONCAT(courses_id) AS courses FROM student_courses WHERE student_id=2 GROUP BY student_id"); $result?=?explode(',',?$row['courses']);?
SELECT?student_id, GROUP_CONCAT(courses_id SEPARATOR?'|||')?AS courses?FROM?student_coursesWHERE?student_id=2?GROUP?BY?student_id; +------------+---------+? | student_id | courses |? +------------+---------+? |?2 ?|?3|||4|||5?| +------------+---------+? 3.除此之外,还可以对这个组的值来进行排序再连接成字符串,例如按courses_id降序来排: SELECT?student_id, GROUP_CONCAT(courses_id?ORDER?BY?courses_id DESC)?AS courses?FROMstudent_courses?WHERE?student_id=2?GROUP?BY?student_id; +------------+---------+? | student_id | courses |? +------------+---------+? |?2?|?5,4,3?| +------------+---------+? 4.需要注意的:
原文地址:Mysql函数GROUP_CONCAT, 感谢原作者分享。