[MySql] Database Constraints

  • NOT NULL - Indicates that a column cannot store NULL values.
  • UNIQUE - Guarantees that each row of a column must have a unique value.
  • DEFAULT - specifies the default value when no value is assigned to the column.
  • PRIMARY KEY - A combination of NOT NULL and UNIQUE. Ensuring that a column (or a combination of two or more columns) is uniquely identified makes it easier and faster to find a specific record in a table.
  • FOREIGN KEY - guarantees referential integrity where data in one table matches values ​​in another table
//设计一个班级表
create table classes(
    classNumber varchar(5) primary key,//主键
    amountOFStudent int not null,      //人数不能为空
    teacherName varchar(10) unique     //每个班级的班主任唯一
);
//设计一个学生表
create table students(
    id varchar(19) primary key,   //id列设置为表的主键
    name varchar(10) not null,    //name列在插入数据时不能为空
    sex varchar(5) default '保密',//sex列在插入数据为空时,默认赋值为'保密'
    classNumber varchar(5),
    foreign key(classNumber) references classes(classNumber) 

    //设置学生表的外键为classNumber,关联班级表的classNumber
    //设置外键语法为:foreign key (字段名) references 主表(列)
);

Guess you like

Origin blog.csdn.net/weixin_67719939/article/details/131690739