DISTINCT,COUNT(*),GROUP_BY,HAVING的联合使用

一、distinct用于获得表中某一列或多列不重复数据,其既可以作用于单列也可以作用于多列,使用时其必须要放置于查询语句的开头,distinct语句中select显示的字段只能是distinct指定的字段,其他字段是不可能出现的。

二、count(*)  函数返回在给定的选择中被选的行数,语法:select  count(*) from  table

例如:有student_course表如下

1.查询course_id为17759的课程下,学生一共有多少种报班情况
select distinct user_id, class_id from student_course where course_id = `17759`;

2.查询course_id为17759的课程下,报了2个或2个以上班级的学生

select user_id , count(*) as c from (

                      select distinct user_id, class_id from student_course where course_id = `17759`

                                                       )  as tmp

group by   user_id  having c >1 order by user_id;

猜你喜欢

转载自blog.csdn.net/u012460314/article/details/88352463