Talk about database constraints

constraint

  • Concept: The data in the table are defined to ensure the accuracy, effectiveness and integrity of data.
  • Category: ① primary key constraint:. Primary key ② non-null constraint:. Not null③ unique constraints:.. Unique ④ foreign key constraint: foreign key
  • Non-empty constraint : not null, the value can not be null
--创建表时添加约束
CREATE TABLE stu(
		id INT,
		NAME VARCHAR(20) NOT NULL
   );
--创建表完后,添加非空约束
ALTER TABLE stu MODIFY NAME VARCHAR(20) NOT NULL;
--删除name的非空约束
ALTER TABLE stu MODIFY NAME VARCHAR(20);
  • The only constraint : unique, value can not be repeated
--创建表时,添加唯一约束
CREATE TABLE stu(
		id INT,
		phone_number VARCHAR(20) UNIQUE -- 添加了唯一约束			
);
--注意mysql中,唯一约束限定的列的值可以有多个null
				
--删除唯一约束
ALTER TABLE stu DROP INDEX phone_number;
		
--在创建表后,添加唯一约束
ALTER TABLE stu MODIFY phone_number VARCHAR(20) UNIQUE;
  • Primary key constraint : Primary Key
    1) When you create a table, add a primary key constraint
create table stu(
	id int primary key,-- 给id添加主键约束
	name varchar(20)
);

2) Drop Primary: ALTER TABLE stu DROP PRIMARY KEY;
3) After creating the table, add the primary key: ALTER TABLE stu MODIFY id INT PRIMARY KEY;
4) automatic growth: If the column is a numeric type, can be done automatically using auto_increment growth

--在创建表时,添加主键约束,并且完成主键自增长
create table stu(
	id int primary key auto_increment,-- 给id添加主键约束
	name varchar(20)
);
--删除自动增长
ALTER TABLE stu MODIFY id INT;
-- 添加自动增长
ALTER TABLE stu MODIFY id INT AUTO_INCREMENT;
  • Note:.. ① a table can have only one primary key field ② primary key is the unique identification of records in the table
  • Foreign key constraint : foreign key, so that the table to produce table relationship, so as to ensure accuracy of the data
  • When you create a table, you can add foreign key syntax is as follows:
create table 表名(
       ....
	  外键列
constraint 外键名称 foreign key (外键列名称) references 主表名称(主表列名称)
);
  • Remove the foreign key:ALTER TABLE 表名 DROP FOREIGN KEY 外键名称;
  • After creating the table, add foreign key
ALTER TABLE 表名 ADD CONSTRAINT 外键名称 FOREIGN KEY (外键字段名称) REFERENCES 主表名称(主表列名称);
  • Cascade operation:
--添加级联:
ALTER TABLE 表名 ADD CONSTRAINT 外键名称 FOREIGN KEY (外键字段名称) REFERENCES 主表名称(主表列名称) ON UPDATE CASCADE ON DELETE CASCADE  ;
--级联更新:
ON UPDATE CASCADE
-- 级联删除
ON DELETE CASCADE
Published 32 original articles · won praise 28 · views 1308

Guess you like

Origin blog.csdn.net/weixin_42369886/article/details/104577268
Recommended