mysql复习

一起复习咯

常见的SQL语言分类:

  1. DDL: 数据定义语言: create alter 等
  2. TPL: 事物处理语言: commit rollback等
  3. DCL: 数据控制语言: grant revoke 等
  4. DML: 数据操作语言: select update insert delete等 》》 这里我们日常最使用最多。

正确使用Join从句

  1. 内连接(INNER) 查询两张表公共的部分。

    1
    select <select_list> from table a inner join table b on a.key = b.key;
  2. 全外连接(FULL OUTER)查询两张表中所有的数据, 或者 查出两张表中非公共部分的的数据。
    不过mysql中不支持全外连接; 我们可以通过union on 对左右外连接 进行查询。 起到同样的效果。

    1
    2
    select <select_list> from table a full outer join table b on a.key = b.key;
    select <select_list> from table a full outer join table b on a.key = b.key where a.key is not null or b.key is not null;
  3. 左外连接(LEFT OUTER)以a表为基础, 可以查出a表中所有的数据(b表如没有数据则对应null), 当然也可以查出a表和b表中共有的(即去除掉b表中null对应的数据行)。

    1
    2
    select <select_list> from table a left join table b on a.key = b.key;
    select <select_list> from table a left join table b on a.key = b.key where b.key is not NULL;
  4. 右外连接(RIGHT OUTER) 和左外连接相反

    1
    2
    select <select_list> from table a right join table b on a.key = b.key;
    select <select_list> from table a right join table b on a.key = b.key where a.key is not NULL;
  5. 交叉连接(CROSS JOIN): 笛卡尔积: a * b, 实际应用中尽量避免这种交叉连接。

    1
    select * from table a cross join table b;

    使用join优化子查询。 优化聚合查询。

    where group by order by 执行顺序

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    当一个查询语句同时出现了where,group by,having,order by的时候,
    执行顺序和编写顺序是:

    1.执行where xx对全表数据做筛选,返回第1个结果集。
    2.针对第1个结果集使用group by分组,返回第2个结果集。
    3.针对第2个结果集中的每1组数据执行select xx,有几组就执行几次,返回第3个结果集。
    4.针对第3个结集执行having xx进行筛选,返回第4个结果集。
    5.针对第4个结果集排序。


    Group By 和 Having, Where ,Order by这些关键字是按照如下顺序进行执行的:
    1. Where,
    2. Group By,
    3. Select(对每个分组执行)
    4. Having
    5. Order by


    看一个例子:
    要求:
    按由高到低的顺序显示个人平均分在70分以上的学生姓名和平均分,
    为了尽可能地提高平均分,在计算平均分前不包括分数在60分以下的成绩,并且也不计算小明的成绩。

    分析:
    1.要求显示学生姓名和平均分
    确定第1步select s_name,avg(s_score) from student;

    2.计算平均分前不包括分数在60分以下的成绩,并且也不计算小明的成绩
    确定第2步 where s_score>=60 and s_name!='xiaoming'

    3.显示个人平均分
    相同名字的学生(同一个学生)考了多门科目 因此按姓名分组,
    确定第3步 group by s_name

    4.显示个人平均分在70分以上
    确定第4步 having avg(s_score)>=70

    5. 由高到低顺序显示
    确定第5步 order by avg(s_score) desc

    完整语句如下:
    select s_name, avg(s_score)
    from student
    where score >= 60 and s_name != 'xiaoming'
    group by s_name having avg(s_score) >= 70
    order by avg(s_score) desc;