mysql分組查詢 總結

2022-09-11 05:57:08 字數 2232 閱讀 7141

分組查詢

語法:select 查詢列表

from 表

【where 篩選條件】

group by 分組的字段

【order by 排序的字段】;

特點:1、和分組函式一同查詢的字段必須是group by後出現的字段

2、篩選分為兩類:分組前篩選和分組後篩選

針對的表       位置        連線的關鍵字

分組前篩選 原始表     group by前         where

分組後篩選 group by後的結果集    group by後         h**ing

問題1:分組函式做篩選能不能放在where後面

答:不能

問題2:where——group by——h**ing

一般來講,能用分組前篩選的,盡量使用分組前篩選,提高效率

3、分組可以按單個欄位也可以按多個字段

4、可以搭配著排序使用

#引入:查詢每個部門的員工個數

select count(*) from employees where department_id=90;

#1.簡單的分組

#案例1:查詢每個工種的員工平均工資

select **g(salary),job_id

from employees

group by job_id;

#案例2:查詢每個位置的部門個數

select count(*),location_id

from departments

group by location_id;

#2、可以實現分組前的篩選

#案例1:查詢郵箱中包含a字元的 每個部門的最高工資

select max(salary),department_id

from employees

where email like '%a%'

group by department_id;

#案例2:查詢有獎金的每個領導手下員工的平均工資

select **g(salary),manager_id

from employees

where commission_pct is not null

group by manager_id;

#3、分組後篩選

#案例:查詢哪個部門的員工個數》5

#①查詢每個部門的員工個數

select count(*),department_id

from employees

group by department_id;

#② 篩選剛才①結果

select count(*),department_id

from employees

group by department_id

h**ing count(*)>5;

#案例2:每個工種有獎金的員工的最高工資》12000的工種編號和最高工資

select job_id,max(salary)

from employees

where commission_pct is not null

group by job_id

h**ing max(salary)>12000;

#案例3:領導編號》102的每個領導手下的最低工資大於5000的領導編號和最低工資manager_id>102

select manager_id,min(salary)

from employees

group by manager_id

h**ing min(salary)>5000;

#4.新增排序

#案例:每個工種有獎金的員工的最高工資》6000的工種編號和最高工資,按最高工資公升序

select job_id,max(salary) m

from employees

where commission_pct is not null

group by job_id

h**ing m>6000

order by m ;

#5.按多個字段分組

#案例:查詢每個工種每個部門的最低工資,並按最低工資降序

select min(salary),job_id,department_id

from employees

group by department_id,job_id

order by min(salary) desc;

mysql 分組查詢

create table wz id int 10 unsigned not null auto increment,province varchar 8 not null default city varchar 32 not null default hphm varchar 8 not nul...

mysql 分組查詢

分組函式,又稱聚合函式,是將一類資料統計後獲得乙個值 1.計算 sum 求和 g 平均值 max 最大值 min 最小值 count 個數 不管什麼引擎下,count 效率最高 以上函式忽略null值 2.distinct 去重 sum distinct id 先去重,再求和。3.group by ...

mysql分組查詢效能優化 MySQL分組查詢優化

我有三個表 類別,文章和article events,具有以下結構 categories id,name 100,000 rows articles id,category id 6000 rows article events id,article id,status id 20,000 rows...