# UNIQUE 唯一性约束
CREATE DATABASE dbtest;
use dbtest;
# 复合约束 (创建时)
CREATE TABLE user(
id INT,
`name` VARCHAR(15),
`password` VARCHAR(15),
CONSTRAINT uk_user_name_pwd UNIQUE(`name`,`password`)
);
INSERT INTO USER
VALUES(1,'A','123');
INSERT INTO USER
VALUES(1,'A1','123');
#复合约束只需要后者内容不与前者完全一样即可。
#删除约束(删除只能用修改命令)
ALTER TABLE user
DROP INDEX uk_user_name_pwd;
#查询表约束
SELECT * FROM information_schema.table_constraints WHERE table_name = '表名称';
#PRIMARY KEY 主键约束
#一个表中只能有一个主键约束
#在创建时添加约束
CREATE TABLE test1(
id INT PRIMARY KEY,
last_name VARCHAR(15),
salary INT,
email VARCHAR(15)
);
INSERT INTO test1
VALUES(1,'Als',5000,'Als@gmail.com');
INSERT INTO test1
VALUES(2,'Als',5000,'Als@gmail.com');
INSERT INTO test1
VALUES(NULL,'Als',5000,'Als@gmail.com');
#一旦某个字段成为主键约束,则这个字段非空,用于唯一的标识表中的一条记录
# 复合主键约束
CREATE TABLE test666 (
id INT,
`name` VARCHAR(10),
`password` VARCHAR(25),
PRIMARY KEY (`name`,`password`)
);
DESC test666;
INSERT INTO test666
VALUES (1,'Alex','abc');
INSERT INTO test666
VALUES (1,'Alex1','abc');
INSERT INTO test666
VALUES (1,'Alex',NULL);
#复合主键约束中复合的任何一个部分都不能为空