#UNIQUE 唯一性约束
CREATE DATABASE db;
use db;
SELECT DATABASE();#查询当前使用的数据库
#复合约束 两个合一个
-- 表级约束
CREATE table user(
id int,
`name` VARCHAR(15),
`password` VARCHAR(25),
CONSTRAINT uk_user_name_pwd UNIQUE(`name`,`password`)
);
DESC user;
SELECT * from information_schema.TABLE_CONSTRAINTS#查询数据库下所有信息
where table_name='user';#查询具体信息
INSERT INTO user
VALUES(1,'Tom','abc');
SELECT * from user;
#可以执行,name,password两个有一个不同就可以运行
INSERT INTO user
VALUES(1,'Tom1','abc');
UPDATE user
set password=null
where id=1;
#删除唯一性约束
SELECT*from information_schema.TABLE_CONSTRAINTS
where table_name='user';
#删除约束
ALTER table user
DROP INDEX uk_user_name_pwd;
#PRIMARY KEY 主键约束
#在 CREATE table 时添加约束
#一个表中只能有一个主键约束(通常把id当成主键约束)
CREATE TABLE test3(
id int PRIMARY KEY,#列级约束
last_name VARCHAR(520),
salary int,
email VARCHAR(521)
);
desc test3;
#一旦某个字段成为主键约束,则这个字段非空,用于唯一的标识表中的一条记录
CREATE TABLE test4(
id int,#列级约束
last_name VARCHAR(520),
salary int,
email VARCHAR(521),
CONSTRAINT pr_test4_id PRIMARY key(id)
);
SELECT*from information_schema.TABLE_CONSTRAINTS
where table_name='test4';
INSERT into test4
VALUES(4,'Tom',5000,'abc#163.com');
SELECT * from test4;
#复合主键约束
CREATE table fuhe(
id int,
name VARCHAR(10),
password VARCHAR(25),
PRIMARY key (name,password)
);
DESC fuhe;
INSERT into fuhe
VALUES(1,'Tom','abc');
SELECT*from fuhe;
#password不能为空
INSERT into fuhe
VALUES(1,'Tom6',null);