每天学习一点点,进步一点点,努力给自己、给我爱的人一个更好的未来!
---- zc
一个需求,查询每个班级中学生数量,并且判断该班级年龄有没有20的
主要用到GROUP_CONCAT关键字,下面例子
一张表:
sql:
create table `student` (
`id` int (11),
`sname` varchar (96),
`saddress` varchar (192),
`age` int (11),
`stu_class` varchar (96)
);
insert into `student` (`id`, `sname`, `saddress`, `age`, `stu_class`) values('1','张三','北京','18','一班');
insert into `student` (`id`, `sname`, `saddress`, `age`, `stu_class`) values('2','里斯','天津','23','一班');
insert into `student` (`id`, `sname`, `saddress`, `age`, `stu_class`) values('3','王五','天津','33','一班');
insert into `student` (`id`, `sname`, `saddress`, `age`, `stu_class`) values('4','赵六','北京','20','三班');
insert into `student` (`id`, `sname`, `saddress`, `age`, `stu_class`) values('5','天气','北京','20','三班');
insert into `student` (`id`, `sname`, `saddress`, `age`, `stu_class`) values('6','王八','河北','19','二班');
insert into `student` (`id`, `sname`, `saddress`, `age`, `stu_class`) values('7','李四','上海','23','三班');
insert into `student` (`id`, `sname`, `saddress`, `age`, `stu_class`) values('8','天齐','河南','23','一班');
insert into `student` (`id`, `sname`, `saddress`, `age`, `stu_class`) values('9','风格','河北','19','二班');
sql:
SELECT COUNT(1) countNum, sname,saddress,stu_class,
GROUP_CONCAT(age ORDER BY age) ageArr
FROM student
GROUP BY stu_class
结果:
其年龄就是排序的
GROUP_CONCAT会得到这样一个字符串“18,23,23,33”,需要分割 split
如果在js中
//假设data是调用接口返回的数据
data.forEach(function(value,index,array){
var arr = value.ageArr.split(",");
//如果年龄中有20,则返回其下标,-1为没有
if (arr.indexOf("20") == -1) {
//TODO
}
});
总体有点乱,但不难理解,因为项目中需要该思想,需要判断,找了些资料,所以记录一下