1. 程式人生 > 其它 >MySQL去重與子查詢and聚合和group by 分組

MySQL去重與子查詢and聚合和group by 分組

去重與子查詢and聚合

1、DISTINCT 去重

select distinct 欄位名 from 表名

select distinct age from user;

2、子查詢(查詢的條件還是一條SQL語句)

select * from 表名 where 欄位名 in (SQL語句)

select * from user where age in(select age from user where id in(1,3,5));

3、聚合函式

  • count 統計
  • max 最大值
  • min 最小值
  • sum 求和
  • avg 求平均數

select count(*),max(age), min(age), sum(age), avg(age) from user;

group by 分組

1、主體結構

select count(欄位名) from 表名 group by 欄位名

2、使用 無條件

  • 統計男生女生分別有多少人

    select sex,count(*) from user group by sex;

  • 統計每個班級有多少人

    select grade, count(*) from user group by grade;

  • 統計每個班級的男生和女生分別有多少人

    select grade,sex, count(*) from user group by grade,sex;

3、having 條件字句

  • 查詢班級人數大於2人

    select grade,count(*) as count from user group by grade having count>2;

  • 檢視python35和python36班級的人數

    select grade,count(*) as count from user group by grade having grade in('python35', 'python36');

  • 檢視python35和python36班級的人數 人數大於2人

    select grade,count(*) as count from user group by grade having grade in('python35', 'python36') and count > 2;