【SQL Server】concat、concat_ws、group_concat用法

concat
用途:连接一个或多个字符串
语法:concat(str1,str2…)
eg:

>>>select concat('aa','bb','cc')
>aabbcc

concat_ws
用途:使用固定连接符连接一个或多个字符串
语法:concat(separator,str1,str2…)
eg:

>>>select concat_ws('-','aa','bb','cc')
>aa-bb-cc

group_concat
用途:分组连接一个或多个字符串
语法:group_concat([DISTINCT] 连接字段名 [Order BY ASC/DESC 排序字段] [Separator ‘分隔符’])
注意:需要和group by结合使用
eg:

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

eg:查找学生ID为2所选的课程

SELECT student_id, courses_id FROM student_courses WHERE student_id=2

【SQL Server】concat、concat_ws、group_concat用法_第1张图片

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

【SQL Server】concat、concat_ws、group_concat用法_第2张图片
分隔符还可以自定义,默认是以“,”作为分隔符,若要改为“|||”,则使用SEPARATOR来指定,例如:

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

除此之外,还可以对这个组的值来进行排序再连接成字符串,例如按courses_id降序来排:

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

你可能感兴趣的:(SQL,Server)