大纲
- 基本概念:数据库=文件夹 表=文件
- sql:操作所有关系型数据的语句
- DDL语句
- DML语句
- DQL语句
- 约束
DDL语句
##数据库操作
- 创建:
create database if not exists + 库名;
2.选择
use+库名;
3.删除
drop database +名;
4.修改
alter database +名 character set utf8;
##表操作
1.创建
create table stu(
age int,
name varchar(255),
birth date
)default charset = utf8;
2.删除
drop table + stu;
3.修改
alter table stu character set utf8;#修改字符集
alter table stu modify age int primary;
alter table stu rename to + 名;#重命名
4.查询
desc + 表名;#查询表结构;
5.添加
alter table stu add +列名+类型;
create table stu like + 名;#复制表
DML语句
##数据操作
1.增加:
insert into +stu(age,name) values(11,"小李");
2.删除
delete from stu where age = 11;
truncate table stu;#删除后重建一个新的
3.修改
update stu set age = 33;
DQL语句(查询语句)
1.条件查询
select * from stu where (age>1/age in (22,55,33)/is null/is not null/between 20 and 30);
select age ,name,age+age as 第三列 from stu;
2.模糊查询
select * from stu where name like "%马_";#%任意多个字符 _任意一个字符。
3.排序查询
select * from stu order by math desc english desc;#降序asc 升序,第二条件只有在第一条件相等时才行
4.聚合函数(对一列数据纵向计算)
count,max,min,avg, sum
select count(age) from stu;
5.分组查询
select count(name) from stu where age>10 group by age;#group by 放最后
6.分页查询
limit 开始索引,条数;
select * from stu limit 0,2;
约束
1.非空约束
name varchar(20) not null;
2.唯一约束
name varchar(20) unique;
3.主键约束
id int primary key auto_increment#自动增长的主键约束
4.外键约束
cid int,
constraint + 外键名 + foreign + key(外键列名)+reference +主表名(主表列名);
cid int,
constraint + 外键名 + foreign + key(外键列名)+reference +主表名(主表列名)+on update cascade;#级联更新
cid int,
constraint + 外键名 + foreign + key(外键列名)+reference +主表名(主表列名)+on delete cascade;#级联删除
后添加:
alter table stu add constraint +键名+ foreign key(cid) reference 主表名(主表列名);