数据库 (三)多表联查

数据库

关键字

  1. from:找到表
  2. where:拿着where指定的约束条件,去文件表中取出一条条记录
  3. group by:将取出的一条条记录进行分组group by,如果没有group by,则整体作为一组
  4. select:执行select
  5. distinct:去重
  6. having:将分组的结果进行having过滤
  7. order by:将结果按条件排序:order by
  8. limit:限制结果的显示条数

null和not null

Null

select 条件 *from 表名where name is null;

not null

create table 表名(列1 列约束,列2 varchar(32)not null default'')charset= utf8

单表操作

分组

group by:

分组是的是:将所有记录按照某个相同字段进行分类,比如针对员工信息的用法:

select 聚合函数,选取的字段from employee group by 分组的字段;

group by 必须和聚合函数(count)出现

min:求最小

max:求最大

sum:求和

count:计数,数量

avg:平均数

having: 表示group by 之后的数据,进行再一次的筛选

asc: order by 字段名asc(升序)

desc: order by 字段名desc(降序)

limit:分页 limit offset,size

offset: 行数据索引

size: 取多少条数据

总结

使用的顺序:

select *from 表名 where 条件group by 条件 having 条件order by 条件 limit 条件;

where>group by > having > order by > limit

多表操作

外键

使用原因:

  1. 减少占用空间、

  2. 只需要修改department表中一次,其余的表中的数据就会相应的修改

一对多:

使用方法:constraint 外键名 foreign key (被约束的字段) references 约束的表(约束的字段)

多对多:

使用方法: constraint 表1 表二foreign key(列明) references 列明

一对一:

constraint 表名 foring key(列名) references 表名(列明),unique(列明)charset = utf8

多表联查

  1. 多表连接查询:

    语法:select 字段列表 from 表1 inner/left/right join 表2 on 表1 .字段=表2.字段;

  2. 内连接:

    select employee.列名 from employee inner join department on employee.列明 =department.列名

  3. 左连接:

    select employee.列名,employee.列名,department.列名 as 列名 from employee left join department on employee.列名=department.列名;

  4. 右连接:

    select employee.列名,employee.列名,department.列名 as 列名 from employee right join department on employee.列名=department.列名;

  5. 全连接(显示左右两边的全部记录):

    select *from employee left join department on employee.列名=department.列名

我把月亮戳到天上 天就是我的 我把脚踩入地里 地就是我的 我亲吻你 你就是我的
原文地址:https://www.cnblogs.com/zhulipeng-1998/p/12863926.html