详解MySQL中的分组查询与连接查询语句_MySQL
详解MySQL中的分组查询与连接查询语句_MySQL 分组查询 group by 1)单独使用 select * from employee group by sex; 将只显示男女两条记录。 2)与group_concat()函数一起使用 select sex,group_concat(name) from employee group by sex; 显示结果中“女”会显示所有sex为“女”的名字name sex | group_concat(name)女 | 小红,小兰男 | 张三,王五,王六 3)与集合函数一起使用 select sex,count(sex) from employee group by sex; 结果: sex | count(num)女 | 1男 | 3 count()为计算个数的方法。 4)与having一起使用 select sex,count(sex) from employee group by sex having count(sex) >= 3; 结果: sex | count(sex)男 | 3 “having条件表达式”作用于分组后的记录。 5)按多字段进行分组 select * from employee group by d_id,sex; 查询结果先按d_id分组,再按sex进行分组 6) 与with rollup一起使用 select sex,count(sex) from employee group by sex with rollup; 结果: sex | count(sex)女 | 1男 | 5null | 6 如果是字符串的话,比如姓名就会生成“张三,李四,王五”这种类型的结果,即name总和。 连接查询 1)内连接查询: 代码如下: select num,name,employee.d_id,age,d_name from employee,department where employee.d_id = department.d_id 因字段名相同,所以取d_id字段值时最好指定哪张表的字段。 2)外连接查询 代码如下: select num,name,employee.d_id,age,d_name from employee left join department on employee.d_id = department.d_id; 右连接查询: PS:使用集合函数查询 select count(*) from employee; 与group by一起使用 select d_id,count(*) from employee group by d_id; 上述语句会先分组后统计 2) sum()函数 select num,sum(score) from grade where num= 1001;select num,sum(score) from grade group by num; sum()只能计算数值类型字段。 select avg(age) from employee;select course,avg(score) from group by course; 4)max(),min()函数 select max(age) from employee;select num,course,max(score) from grade group by course; 对于字符串的最大值问题,max()函数是使用字符对应的ascii码进行计算的。 以上就是详解MySQL中的分组查询与连接查询语句_MySQL的内容, |