SQL表的创建与约束3.0



SQL表的创建与约束

1.SQL语言分为4类:

DQL:数据查询语言

DML:数据操作语言,对数据的增删改

DDL:数据定义语言

TCL

 

desc stus查看表结构

insert into stus values (1,'abc',12)

insert into stus(name,age) values('bb',13)

插入一条数据

delete from stus

删除数据

delete from stus where id=3

更新记录

update stus set name='aa',age=12 where id=2

 

2.创建表

create table ttt(

类型

id int(6),

name varchar(100),

score double(5,2),

birth date

)

清空表

truncate table stus

删除一张表

drop table ttt

表的修改

修改表名

alter table stus

rename to sss

修改

alter table sss

change column age sage int(10)

alter table sss

drop column sage

增加列

alter table sss

add column age int(10)

 

3.约束

约束是在表的数据列上强制执行的规则。这些是用来限制可以插入到表中的数据类型。这确保了数据库中数据的准确性和可靠性。

约束可以是列级或表级。列级约束仅适用于列,表级约束被应用到整个表。

以下是在 SQL 中常用的约束。

NOT NULL 约束:确保某列不能有 NULL 值。

DEFAULT 约束:当某列没有指定值时,为该列提供默认值。

UNIQUE 约束:确保某列中的所有值是不同的

PRIMARY Key 约束:唯一标识数据库表中的各行/记录。

CHECK 约束:CHECK 约束确保某列中的所有值满足一定条件。

create table ss(

id int(10) primary key auto_increment, //主键约束

name varchar(100) unique, //唯一约束

birth date not null //非空约束

)

 

create table sts(

id int(10) primary key auto_increment,

name varchar(100) not null,

teacher int(10),

foreign key(teacher) references ss(id) //外键约束

)

 

增加外键约束

alter table ss

add constraint primary key auto_increment(id)

增加唯一约束

alter table ss

add constraint unique(name)

增非空约束alter table ss

change column name name varchar(100) not null

删除name的约束

alter table ss drop index name

约束不难只是需要花时间理解

 

猜你喜欢

转载自blog.csdn.net/qq_42293835/article/details/80953303