用于将多个字符串连接成一个字符串。将一班学生的学号、学名姓名、别名三个字段拼接起来。
CREATE TABLE `student` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`stu_id` int(11) NOT NULL,
`stu_name` varchar(32) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT ‘学生姓名‘,
`alias` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT ‘别名‘,
`cls_id` int(11) NULL DEFAULT NULL COMMENT ‘班级ID‘,
PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic;
INSERT INTO `student`(`id`, `stu_id`, `stu_name`, `alias`, `cls_id`) VALUES (1, 1001, ‘赵云‘, ‘‘, 1);
INSERT INTO `student`(`id`, `stu_id`, `stu_name`, `alias`, `cls_id`) VALUES (2, 1002, ‘张飞‘, NULL, 1);
INSERT INTO `student`(`id`, `stu_id`, `stu_name`, `alias`, `cls_id`) VALUES (3, 1003, ‘关羽‘, ‘美髯公‘, 1);
INSERT INTO `student`(`id`, `stu_id`, `stu_name`, `alias`, `cls_id`) VALUES (4, 2001, ‘司马懿‘, NULL, 2);
INSERT INTO `student`(`id`, `stu_id`, `stu_name`, `alias`, `cls_id`) VALUES (5, 2002, ‘夏侯惇‘, NULL, 2);
concat
方法返回的结果为连接参数产生的字符串。
null
,则返回值为null
。select concat( cast( column1 as char ), column2 )
SELECT
stu_id,
stu_name,
alias,
concat( stu_id, stu_name, alias ) AS stu_info
FROM
student
WHERE
cls_id=1
concat_ws
方法是concat
的特殊形式。第一个参数指定分隔符,分隔符可以是一个字符串,也可以是其他参数。
SELECT
stu_id,
stu_name,
alias,
concat_ws( ‘,‘, stu_id, stu_name, alias ) AS stu_info
FROM
student
WHERE
cls_id =1
原文:https://www.cnblogs.com/lucky9322/p/14052408.html