Mysql的GROUP_CONCAT()函數使用方法_PHP教程

來源:互聯網
上載者:User
文法:

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

下面示範一下這個函數,先建立一個學生選課表student_courses,並填充一些測試資料。

SQL代碼
複製代碼 代碼如下:
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);


若要尋找學生ID為2所選的課程,則使用下面這條SQL:

SQL代碼
複製代碼 代碼如下:
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)


輸出結果有3條記錄,說明學生ID為2的學生選了3、4、5這3門課程。
放在PHP裡,必須用一個迴圈才能取到這3條記錄,如下所示:



PHP代碼
複製代碼 代碼如下:
foreach ($pdo->query("SELECT student_id, courses_id FROM student_courses WHERE student_id=2") as $row) {
$result[] = $row['courses_id'];
}

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



SQL代碼
複製代碼 代碼如下:
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代碼
複製代碼 代碼如下:
$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']);


分隔字元還可以自訂,預設是以“,”作為分隔字元,若要改為“|||”,則使用SEPARATOR來指定,例如:



SQL代碼
複製代碼 代碼如下:
SELECT student_id, GROUP_CONCAT(courses_id SEPARATOR '|||') AS courses FROM student_courses WHERE student_id=2 GROUP BY student_id;

除此之外,還可以對這個組的值來進行排序再串連成字串,例如按courses_id降序來排:

SQL代碼
複製代碼 代碼如下:
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;

http://www.bkjia.com/PHPjc/318754.htmlwww.bkjia.comtruehttp://www.bkjia.com/PHPjc/318754.htmlTechArticle文法: GROUP_CONCAT([DISTINCT]expr[,expr...][ORDERBY{unsigned_integer|col_name|expr}[ASC|DESC][,col_name...]][SEPARATORstr_val]) 下面示範一下這個函數,先建立一個學...

  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    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.