当前位置:网站首页>Summary of common constraints in MySQL foundation part I

Summary of common constraints in MySQL foundation part I

2022-06-11 10:29:00 Jingxuan

1. Overview of constraints

1.1 Why do we need constraints ?

     Data integrity (Data Integrity) Refers to the of data Accuracy (Accuracy) and reliability (Reliability) It is to prevent the existence of Do not conform to the Semantically defined data and prevent Caused by input and output of error messages Invalid operation Or error messages . in order to Guarantee Data integrity ,SQL The specification defines table data in a constrained manner Additional conditionality .
     Consider from the following four aspects :

Entity integrity (Entity Integrity) : for example , In the same table , There can't be two identical records that can't be distinguished
Domain integrity (Domain Integrity) : for example : Age range 0-120, Gender range “ male / Woman ”
Citation integrity (Referential Integrity) : for example : Employee's Department , Find this department in the Department list
User-defined integrity (User-defined Integrity) : for example : Unique user name 、 The password cannot be empty , The salary of the manager of the Department shall not be higher than the average salary of the employees of the Department 5 times .

1.2 What are constraints ?

     Constraints are table level A mandatory provision . When creating the table, it is Column level constraints and Table level constraints , Column level constraint refers to appending constraint conditions after columns , Table level constraint means that after all fields are written , Write constraints on a single line .
     You can specify constraints when you create a table ( adopt CREATE TABLE sentence ), Or, after the table is created, through ALTER TABLE sentence Stipulate constraints .

1.3 Classification of constraints

(1) According to the restrictions of constraint data columns

① Single column constraints : Each constraint constrains only one column
② Multi column constraint : Each constraint can constrain multiple columns of data

(2) According to the scope of the constraint

① Column level constraints : Can only act on one column , Follow the definition of the column
② Table level constraints : Can act on multiple columns , Not with columns , It is defined separately

(3) According to the function of constraints

①NOT NULL Non empty constraint , Specifies that a field cannot be empty
②UNIQUE Unique constraint , Specify that a field is unique in the whole table
③PRIMARY KEY Primary key ( Non empty and unique ) constraint
④FOREIGN KEY Foreign key constraints
⑤CHECK Check constraint
⑥DEFAULT Default constraint

View the existing constraints of a table

#information_schema Database name ( System libraries ) 
#table_constraints The name of the table ( Store constraints for individual tables )
SELECT * FROM information_schema.table_constraints
 WHERE table_name = ' The name of the table ';

2. Non empty constraint (NOT NULL)

2.1 Overview of non empty constraints

(1) effect

     Limit a field / The value of a column cannot be empty

(2) keyword

    NOT NULL

(3) characteristic

① Default , All types of values are It can be NULL, Include INT、FLOAT And so on
② Non empty constraints can only appear in Columns of table objects On , Can only A column qualifies separately Non empty , Cannot combine non empty
③ A table can have many columns, which are limited to non empty
④ An empty string ’' It's not equal to NULL,0 Also is not equal to NULL

2.2 Add non empty constraints

(1) Build table

Grammar format :

CREATE TABLE  The name of the table (
  Field name   data type ,  Field name   data type  NOT NULL,
  Field name   data type  NOT NULL
);

Use samples :

CREATE TABLE test1(
id INT NOT NULL,
last_name VARCHAR(15) NOT NULL,
email VARCHAR(25),
salary DECIMAL(10,2)
);

 Insert picture description here
(2) After the establishment of the table

Use format :

alter table  The name of the table  modify  Field name   data type  not null;

Use samples :

ALTER TABLE test1
MODIFY email VARCHAR(25) NOT NULl;

 Insert picture description here

2.3 Delete non empty constraints

Use format :

alter table  The name of the table  modify  Field name   data type ;

Use samples :

ALTER TABLE test1
MODIFY email VARCHAR(25) NULL;

 Insert picture description here

3. Uniqueness constraint UNIQUE

3.1 Overview of uniqueness constraints

(1) effect

     Used to restrict a field / The value of a column cannot be repeated .

(2) keyword

    UNIQUE

(3) characteristic

① The same table can have Multiple unique constraints .
② The only constraint can be a column It's worth it , You can also combine multiple columns to have unique values .
③ Uniqueness constraint Allow column value to be empty .
④ When creating unique constraints , If you don't name a unique constraint , The default is the same as the column name .
⑤MySQL A unique constraint column will be created by default unique index .

3.2 Add uniqueness constraints

(1) Build table

Add format :
The way 1:

create table  The name of the table ( 
 Field name   data type , 
 Field name   data type  unique, 
 Field name   data type  unique key, 
 Field name   data type 
 );

Mode two :

create table  The name of the table ( 
 Field name   data type , 
 Field name   data type , 
 Field name   data type ,
 [constraint  Constraint name ] unique key( Field name ) 
 );

Use samples :

CREATE TABLE test2(
id INT UNIQUE,# Column level constraints 
last_name VARCHAR(15),
email VARCHAR(25),
salary DECIMAL(10,2),
# Table level constraints 
CONSTRAINT uk_test2_email UNIQUE(email)
);

 Insert picture description here

Use the following statement , View the name of the constraint :

SELECT * FROM information_schema.TABLE_CONSTRAINTS
WHERE table_name = 'test2';

 Insert picture description here

INSERT INTO test2(id,last_name,email,salary)
VALUES(1,'Tom','[email protected]',5000);

Inserting the following statement will produce an error :
#1062 - Duplicate entry ‘1’ for key ‘test2.id’

INSERT INTO test2(id,last_name,email,salary)
VALUES(1,'Jerry','[email protected]',5000);

 Insert picture description here

(2) Specify the only key constraint after creating the table
The way 1:

alter table  The name of the table  add unique key( Field list );

The way 2:

  alter table  The name of the table  modify  Field name   Field type  unique;
ALTER TABLE test2
MODIFY last_name VARCHAR(15) UNIQUE;

 Insert picture description here

3.3 Compound unique constraint

Use format :

create table  The name of the table ( 
 Field name   data type , 
 Field name   data type , 
 Field name   data type , unique key( Field list ) # Multiple field names are written in the field list , Multiple field names are separated by commas , It means that it is compound and unique , That is more   The combination of two fields is unique  
);

Use samples :

CREATE TABLE user(
id INT,
name VARCHAR(15),
password VARCHAR(15),
# Adding compound constraints , Table level constraints 
CONSTRAINT uk_test2_name_pwd UNIQUE(name,password)
);

As long as the two fields are not Exactly the same Can be added successfully

INSERT INTO user
VALUES (1,'Tom','abc');
INSERT INTO user
VALUES (1,'Tom','abcd');

 Insert picture description here

3.4 Remove the uniqueness constraint

explain

① Columns that add uniqueness constraints are also automatically Create unique index .
② The only way to delete a unique constraint is through Delete unique index Method to delete .
③ Need to specify when deleting Unique index name , The unique index name is the same as the unique constraint name .
④ If you do not specify a name when creating a unique constraint , If it's a single column , The default is the same as the column name ; If it's a composite column , Then default and () The first column in the list has the same name . You can also customize the uniqueness constraint name .

Delete the sample :

ALTER TABLE test2
DROP INDEX last_name;

 Insert picture description here

Be careful : Can pass show index from The name of the table ; View the index of the table

4. Primary key constraint PRIMARY KEY

4.1 Overview of primary key constraints

(1) effect

     Used to uniquely identify a row of records in the table .

(2) keyword

PRIMARY KEY

(3) characteristic

① The primary key constraint is equivalent to Unique constraint + Non empty constraint The combination of , Primary key constraint column No repetition , also Null values are not allowed .
② One watch is the most There can only be one primary key beam , The primary key constraint can be created in Column level establish , It can also be in Table level To create a .
③ The primary key constraint corresponds to one or more columns in the table ( Composite primary key
④ If it is a multi column combination Composite primary key constraint , So these columns Null values are not allowed , And the combined value is not allowed to repeat .
⑤MySQL The primary key name of is always PRIMARY, Even if you name the primary key constraint name, it's useless .
⑥ When creating a primary key constraint , By default, the system will establish a corresponding column on the column or column combination primary key ( That can be queried according to the primary key , Query according to the primary key , More efficient ). If the primary key constraint is deleted , The index corresponding to the primary key constraint is automatically deleted .
⑦ One thing to note is that , Do not modify the value of the primary key field . Because the primary key is the unique identification of the data record , If you modify the value of the primary key , It may destroy the integrity of the data .

4.2 Add primary key constraint

(1) Specify the primary key constraint when creating the table

Use format :

Column level constraints

create table  The name of the table ( 
 Field name   data type  primary key, # Column level mode  
 Field name   data type ,
  Field name   data type  
 );

Table level constraints

create table  The name of the table ( 
 Field name   data type , 
 Field name   data type ,  Field name   data type , 
[constraint  Constraint name ] primary key( Field name ) # Table level mode 
 );

Use examples :

CREATE TABLE test3(
id INT PRIMARY KEY,# Column level constraints 
last_name VARCHAR(15),
salary DECIMAL(10,2),
email VARCHAR(20)
);

 Insert picture description here

CREATE TABLE test4(
id INT,
last_name VARCHAR(15),
salary DECIMAL(10,2),
email VARCHAR(20),
# Table level constraints 
CONSTRAINT pk_test5_id PRIMARY KEY(id)
);

 Insert picture description here
(2) Add a primary key constraint after creating a table

Use format :

ALTER TABLE  The name of the table  ADD PRIMARY KEY( Field list ); # The field list can be a field , It can also be multiple fields , If it is more   If there are two fields , The primary key is compound 
CREATE TABLE test6(
id INT,
name VARCHAR(15),
salary DECIMAL(10,2),
email VARCHAR(25)
);
ALTER TABLE test6
MODIFY id INT PRIMARY KEY;

 Insert picture description here
 Insert picture description here

4.3 Composite primary key

Use format :

create table  The name of the table ( 
 Field name   data type ,
  Field name   data type ,
   Field name   data type , 
  primary key( Field name 1, Field name 2) # Represents the field 1 And field 2 The combination is unique , You can also have more fields  
  );

Use samples :
Student list

create table student(
sid int, # Student number  
sname varchar(20), # full name  
tel char(11) unique key, # Telephone  
cardid char(18) unique key # ID number  
);

The curriculum

create table course(
cid int, # Course number  
cname varchar(20) # Course name  
);

Course selection table

create table student_course( 
id int, 
sid int, # Student number 
cid int, # Course number 
score int, 
unique key(sid,cid) # Compound the only  
);

Add students and courses

insert into student values(1,' Zhang San ','13710011002','101223199012015623');# success  
insert into student values(2,' Li Si ','13710011003','101223199012015624');# success  
insert into course values(1001,'Java'),(1002,'MySQL');# success 

 Insert picture description here

 Insert picture description here

Add student elective

When using a composite primary key : The content of the composite primary key Not to be repeated

insert into student_course 
values 
(1, 1, 1001, 89), 
(2, 1, 1002, 90), 
(3, 2, 1001, 88), 
(4, 2, 1002, 56);# success 

 Insert picture description here
Primary key deletion format :

alter table  The name of the table  drop primary key;

     The deletion of primary keys will not be described here , Because they are generally not used in actual use , Be careful when deleting .

原网站

版权声明
本文为[Jingxuan]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/162/202206111018394630.html