一、表的基本介绍
1、数据类型
类型 |
描述 |
Char(长度) |
定长字符串,存储空间大小固定,适合作为主键或外键 |
Varchar(长度) |
变长字符串,存储空间等于实际数据空间 |
double(有效数字位数,小数位) |
数值型 |
Float(有效数字位数,小数位) |
数值型 |
Int( 长度) |
整型 |
bigint(长度) |
长整型 |
Date |
日期型 |
BLOB |
Binary Large OBject(二进制大对象) |
CLOB |
Character Large OBject(字符大对象) |
其它………………… |
|
2、创建表语句
create table t_student(
no int(10) not null unique,
name varchar(32),
sex char(2),
birth date,
email varchar(128)
);
注:表格的名字最好以t_或者 tbl_开始,增强可读性
3、 删除表语句
drop table if exists t_student;
4、 健表加约束 constraint
常见约束:
i1、非空约束,not null
i2、唯一约束 ,unique (不能为空和唯一性的约束可以同时加在同一个字段上,上面在创建表的时候已经演示了)
i3、主键约束 、primary key
i4、外键约束、foreign key
a) not null、unique
// 使用表级约束给多字段联合添加约束
drop table if exists t_user;
create table t_user(
id int(10),
name varchar(32) not null,
email varchar(128),
unique(name,email) ##这里使用name和email共同决定了它的唯一性
);
b) primary key 和 foreign key
primary key:给某个字段添加主键约束primary key之后,该字段不能重复,并且不能为空,主字段还会默认添加“索引-index”
创建主键
drop table if exists t_classes; create table t_classes( classes_id int(3), classes_name varchar(40), constraint pk_classes_id primary key(classes_id) ) |
创建外键
drop table if exists t_student; create table t_student( student_id int(10), student_name varchar(20), sex char(2), birthday date, email varchar(30), classes_id int(3), constraint student_id_pk primary key(student_id), constraint fk_classes_id foreign key(classes_id) references t_classes(classes_id) ) |
二、表的增、删、改
1、增
Insert into 表名(字段,。。。。) values(值,………..) |
insert into emp(empno,ename,job,mgr,hiredate,sal,comm,deptnp) values(9997,'zhangsan','MANAGER','null','1981-06-12',3000,500,10);
2、删
Delete from表名 where 。。。。。 |
delete from emp where comm = 500; ##删除津贴为500的员工信息
3、改
update 表名 set 字段名称1=需要修改的值1, 字段名称2=需要修改的值2 where ……. |
update emp set sal = sal*1.1 where job = 'MANAGER';