首页 小组 文章 相册 留言本 用户 搜索 我的社区 在线学堂 商城 购物车 支付钱包

[打卡]复习·约束

2024-05-21 12:09:27
0
182

#not null 非空约束
-- 只能用列级约束,不能表级约束

#创建数据库
create DATABASE db;
use db;

#在 CREATE TABLE 时添加约束
CREATE TABLE test1(
id int not null,
last_name VARCHAR(15) not null,
email VARCHAR(25),
salary int
);
desc test1;

#插入数据
INSERT into test1
(id,last_name,email,salary)
VALUES
(1,'tan','tanjianci@qq.com',null);

#查看表结构
SELECT*from test1;

#把email变为空值
update test1
set email=null
where id=1;

#把salary变成6000
UPDATE test1
set salary=6000
where id=1;

#在 ALTER TABLE 时添加约束
-- 规则:‘如果’报错,本身有null值,再改为not null时,不能添加
ALTER TABLE test1
MODIFY email VARCHAR(25) not null;

#在 alter table 时删除约束
ALTER TABLE test1
MODIFY last_name VARCHAR(10) NULL;

DESC test1;

CREATE table test2(
id int UNIQUE, #列级约束
last_name VARCHAR(15),
email VARCHAR(25),
salary int,

#表级约束
CONSTRAINT uk_test2_email UNIQUE(email)
);

DESC test2;

SELECT* from test2;

INSERT into test2
(id,last_name,email,salary)
VALUES
(1,'Tom','Tom@163.com',8000);
#id,last_name,email,salary不能与第一条数据冲突
INSERT into test2
(id,last_name,email,salary)
VALUES
(1,'Sam','Tom@163.com',8000);

#在 ALTER TABLE 时添加约束
#方式一:
DESC test2;

alter table test2
ADD CONSTRAINT uk_test2_sal UNIQUE(salary);

#方式二:
alter table test2
MODIFY last_name VARCHAR(20) UNIQUE;

SELECT * FROM information_schema.table_constraints WHERE table_name = 'test2';



评论
意见反馈