黑猴子的家:mysql 表级约束

添加表级约束

1、语法
CREATE TABLE stuinfo(
    id INT ,
    stuName VARCHAR(20),
    gender CHAR,
    age INT UNSIGNED,
    【CONSTRAINT 约束名】约束类型(字段)
);
2、案例
CREATE TABLE grade(
    id INT PRIMARY KEY,
    gradename VARCHAR(20)
)

DROP TABLE IF EXISTS stuinfo;
CREATE TABLE stuinfo(
    id INT NOT NULL,
    stuName VARCHAR(20),
    gender CHAR DEFAULT '男',
    age INT UNSIGNED,
    gradeid INT,
    PRIMARY KEY(id,stuname),#组合主键:id+stuname
    CONSTRAINT uq UNIQUE(age),#唯一键
    CONSTRAINT fk_stuinfo FOREIGN KEY(gradeid) REFERENCES grade(id)#外键约束
);

DESC stuinfo;

SELECT * FROM grade;
3、组合主键
INSERT INTO grade VALUES(1,'一年级'),(2,'二年级'),(3,'三年级');
INSERT INTO stuinfo VALUES(2,'lucy','男',233,1);
4、外键
INSERT INTO stuinfo VALUES(3,'lucy','男',13,10);

你可能感兴趣的:(黑猴子的家:mysql 表级约束)