1.表
1.1表的创建(DDL)
#语法格式CREATE TABLE 表名(字段名 数据类型(长度),字段名 数据类型(长度),字段名 数据类型(长度),字段名 数据类型(长度));
注:char和varchar的区别?
1、char : 长度不会发生改变。可能会浪费空间,但执行速度更快。
2、varchar: 随着字符串本身长度变化而变化。更智能,节省空间。但是效率低。
3、合理选择类型,当数据本身长度不会发生改变的时候,建议使用char类型。例如:个人简介, 这个信息可能是30个字,也可能是200个字,这种空间建议使用varchar。
#创建用户表drop table if exists tbl_user;#当tbl_user表存在的时候删除掉create table tbl_user( id int, name varchar(32), password varchar(32), sex char(1), birth char(10), height float(3,2)#3代表有效数字的个数,2代表小数位的位数 //最后一行结尾处无,);
1.2insert
#insert into 表名(字段名1,字段名2,字段名3,....) values(值1,值2,值3,....);#注意:字段与值必须一一对应,数量要一致,数据类型要一致。insert into tbl_user(id,name,password,sex,birth,height) values (3,'lisi','123','1','1980-10-11','1.8');insert into tbl_user(name,password,sex,birth,id,height)values ('wangwu','456','0','1980-01-11',4,'1.8');insert into tbl_user(name,password) values ('jack','111');insert into tbl_user values (5,'lucy','123','0','1980-10-11','1.6');#前面的字段省略之后,默认是把表当中所有的字段都写上#还有一种写法insert into tbl_user(name) values ('a'),('b'),('c');
1.3表的复制
#以某个查询结果当做表创建。create table dept1 as select * from dept; //方法一create table dept1 like dept; //方法二#将查询结果作为记录插入到某张表当中insert into dept1 select * from dept;
1.4delete
#没有条件会导致所有数据全部删除。delete from 表名 where 条件;
1.5update
#要求将dept1表当中20部门的位置修改为BEIJING,部门名称修改为YANFAYIBUupdate dept1 set dname = 'YANFAYIBU' , loc = 'BEIJING'; // 全部修改update dept1 set dname = 'YANFAYIBU' , loc = 'BEIJING' where deptno = 20;注意:是逗号,不是andupdate dept1 set dname = 'YANFAYIBU' and loc = 'BEIJING' where deptno = 20;#错误
注:
对于所有的DML语句来说都是可以回滚的。
insert
delete
update
除了以上三个语句之外,剩下的所有操作都是不可回滚的
1.6修改表的结构
#添加字段alter table dept1 add tel varchar(255);#删除字段alter table dept1 drop tel;#修改字段alter table dept1 modify loc varchar(23);
2.表的约束
2.1约束分类
约束的目的是为了保证表当中数据的完整性和有效性
常见的约束分类:
- 非空约束(not null)
- 唯一性约束(unique)
- 主键约束(primary key,简称PK)
- 外键约束(foreign key,简称FK)
2.2非空约束
not null 约束表示该字段不能为NULL,插入数据的时候,该字段必须提供具体的数据
drop table if exists tbl_user;create table tbl_user( id int, name varchar(255) not null );desc tbl_user#展示该表的基本结构
2.3唯一约束
unique 约束表示该约束表示字段当中的数据不能重复,但可以为NULL
drop table if exists tbl_user;create table tbl_user( id int, name varchar(255) unique //列级约束);drop table if exists tbl_user;create table tbl_user(id int,name varchar(255),unique(name)// 该约束不是直接添加在某列的后面,称为表级约束);
什么时候使用表级约束?
同时给“多个字段”添加“一个约束”,只能使用表级约束。
drop table if exists tbl_user;create table tbl_user(id int,name varchar(255),unique(id,name));
注:
not null 和 unique可以联合使用
drop table if exists tbl_user;create table tbl_user(id int not null unique, // 表示该字段不能为NULL,也不能重复。两者合并等同于主键约束name varchar(255));
下面的主外键约束在下节中展示,主要是害怕大家没时间一次性读完,望大家可以充分利用碎片化时间,来增长知识!
预祝大家:马到成功!!!! 加油!!!!