欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Mysql的GROUP_CONCAT()函數(shù)使用方法

 更新時(shí)間:2008年03月28日 22:28:33   作者:  
GROUP_CONCAT語法與實(shí)例代碼
語法:

GROUP_CONCAT([DISTINCT] expr [,expr ...][ORDER BY {unsigned_integer | col_name | expr}[ASC | DESC] [,col_name ...]][SEPARATOR str_val])

下面演示一下這個(gè)函數(shù),先建立一個(gè)學(xué)生選課表student_courses,并填充一些測試數(shù)據(jù)。

SQL代碼
復(fù)制代碼 代碼如下:

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);    


若要查找學(xué)生ID為2所選的課程,則使用下面這條SQL:

SQL代碼 
復(fù)制代碼 代碼如下:

mysql> SELECT student_id, courses_id FROM student_courses WHERE student_id=2;     
+------------+------------+     
| student_id | courses_id |     
+------------+------------+     
|          2 |          3 |     
|          2 |          4 |     
|          2 |          5 |     
+------------+------------+     
3 rows IN SET (0.00 sec)  
 

輸出結(jié)果有3條記錄,說明學(xué)生ID為2的學(xué)生選了3、4、5這3門課程。
放在PHP里,必須用一個(gè)循環(huán)才能取到這3條記錄,如下所示:

 

PHP代碼
復(fù)制代碼 代碼如下:

foreach ($pdo->query("SELECT student_id, courses_id FROM student_courses WHERE student_id=2") as $row) {     
    $result[] = $row['courses_id'];     
}     

而如果采用GROUP_CONCAT()函數(shù)和GROUP BY語句就顯得非常簡單了,如下所示:

 

SQL代碼 
復(fù)制代碼 代碼如下:

mysql> SELECT student_id, GROUP_CONCAT(courses_id) AS courses FROM student_courses WHERE student_id=2 GROUP BY student_id;     
+------------+---------+     
| student_id | courses |     
+------------+---------+     
|          2 | 3,4,5   |     
+------------+---------+     
1 row IN SET (0.00 sec)   


這樣php里處理就簡單了:

 

PHP代碼
復(fù)制代碼 代碼如下:

$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']);     


分隔符還可以自定義,默認(rèn)是以“,”作為分隔符,若要改為“|||”,則使用SEPARATOR來指定,例如:

 

SQL代碼
復(fù)制代碼 代碼如下:

SELECT student_id, GROUP_CONCAT(courses_id SEPARATOR '|||') AS courses FROM student_courses WHERE student_id=2 GROUP BY student_id;     

除此之外,還可以對這個(gè)組的值來進(jìn)行排序再連接成字符串,例如按courses_id降序來排:

SQL代碼
復(fù)制代碼 代碼如下:

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;

相關(guān)文章

最新評論