目录
一、SQL语句分类
数据定义语言 DDL | 定义和管理数据对象 如数据库、数据表等 | create、drop、alter |
数据操作语言 DML | 用于操作数据库对象中所包含的数据 | insert、update、delete |
数据查询语言 DQL | 用于数据库数据查询 | select |
数据控制语言 DCL | 用于管理数据库的语言包括管理权限及数据更改 | grant、commit、rollback |
1.DDL
① 创建库 create datebase(if not exists) + 库名
②查看所有库 show databases
③删除库 drop database(if exists) + 库名
④选择库 use+库名 #使用库 切换工作库
⑤创建表
create table + 表名(
字段名 数据类型 索引
)
注意:1、三大范式:拆表与拆字段
1.1、确保每列原子性 不可分割的
1.2、确保表中的每列都和主键相关
1.3、确保每列都和主键列直接相关
(每个字段都不可再分、每个字段都与主键直接相关)
2、索引中包括约束、主键自增等
2.1、表约束
2.1.1、非空约束 not null (只能行内约束)
2.1.2、唯一约束unique(具有唯一性 不可重复,但可为null)
a:可以表级约束unique( , )多个字段同时相等不能重复
b:表级约束可以起名字,方便以后删这个约束
constraint 名字 unique( , )
2.1.3、主键约束 primary key
注意:1、一个表只能有一个主键
2、主键可以复合,表级约束来定义
3、不能修改主键字段的值
4、自增数 auto_increment (必须是整型、主键,可以自定义、
最多只有一个自增)
2.1.4、外键约束 foreign key (表的字段名)references 父表表名(父表字段名)
2.DML(增删改语法)
1、新增
insert into 表名(字段...字段)values/value (值... 值)
2、删除
delete from 表名(删除整个表)
delete from 表名 where + 判断
注:delete 不能清空主键自增
3、修改
update 表名 set 字段名=值,字段名=值..... where 条件判断/=
例如:where name=1 and age= 20
3.DQL(查询)
①查表中的字段
select 字段名,字段名,from 表名
②查询表中的所有字段
select * from 表名
③起别名 as
字段名 as '别名'
字段名 别名
注:1.distinct 去重
④select distinct * from 表名 where 条件判断
⑤like 模糊查询 %在左前模糊 在右后模糊
select * from 表名 where 字段 like '%xxx%'
⑥在特定范围内查询
select 8 from 表名 where 字段 in(x,x,x)
2.聚合函数
2.1 count(*) sum(*) max(*) min(*) aug(*)
例:select count(*),sum(*) from 表名
3.分组、排序、分页
group by 字段名 having 字段
order by 字段名 asc/dese,字段名 asc/dese...
注:排序多写多个字段,先写的优先排
asc 默认 升序可以不写 desc 降序 必须写
limit
select * from 表名 limit 数字名(显示个数)offset 数字名(显示个数)
二、高级查询
多表联查
① select * from 表名,表名 where 条件(数据量小时用(内联))
注:若不写条件得到的表是笛卡尔积数量(若单表数据过大,会导致笛卡尔积过大占内存
②select * from 表名 inner join 表名 on 条件(数据量大时用(外联))
③select *from 表名 left /right join 表名 on条件
④union 查询两个集合的合并、纵向合并
注意:1.数据类型不同可以合并
2.两个集合的字段数量要相同
3.表头第一个表的名字
4.去除重复 union all 不去重
例: select * from 表名 union
子查询
where 子查询(效率低、要多次启动搜索)
注意:所有的子查询都需要用小括号括起来
例:select * from student where sid(select max(sid)from student)
from 子查询
① from()
② from class innex join(子表用()代替)on
exist 子查询
例:select * from teacher where exists (select...)
若子查询不为null,则主查询执行,反之不执行
some连接 any 连续 or and 比较
例:select *from student inner join sc on student.sid = sc.sid where classid =1 and score> some(select min() ... )