当前位置:网站首页>MySQL learning summary 9: non empty constraints, uniqueness constraints, primary key, auto_ Increment, foreign key, default, etc

MySQL learning summary 9: non empty constraints, uniqueness constraints, primary key, auto_ Increment, foreign key, default, etc

2022-06-13 03:24:00 koping_ wu

1、 constraint (constraint) summary

1.1 Why do we need constraints

   Data integrity (Data Integrity) The accuracy of data (Accuracy) And reliability (Reliability). It is proposed to prevent the existence of data that does not comply with the semantic provisions in the database and to prevent invalid operation or error information caused by the input and output of error information .
   In order to ensure the integrity of the data ,SQL The specification imposes additional constraints on table data in a constrained manner . 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 . So when you insert the same data as the database already has , If the corresponding constraint is made, an error can be reported .
  • Domain integrity (Domain Integrity) : for example : Age range 0-120. So if you make a corresponding constraint , When the inserted age data is greater than 120 You can report an error .
  • Citation integrity (Referential Integrity): for example : Employee's Department , Find this department in the Department list . So if you make a corresponding constraint , When you are writing the data of the employee table ( Including employee departments ), If the employee department is not in the Department table , You can report an error .
  • User-defined integrity (User-defined Integrity) : for example : The password cannot be empty . So if you make a corresponding constraint , If the password of the user information you insert is empty, an error can be reported .
      Sum up , When we want to ensure data integrity , If the corresponding constraint is made , Many operations of inserting or modifying data may not be successful at all , Because it violates the constraints defined at the beginning , This will ensure the accuracy and reliability of the data in the database .

1.2 What are constraints

   Constraints are mandatory at the table level .
   You can specify constraints when you create a table ( adopt CREATE TABLE sentence ), Or, after the table is created, through ALTER TABLE Statement specifies a constraint .

1.3 Classification of constraints

1) According to the restrictions of constraint data columns , Constraints can be divided into :

  • 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 , Constraints can be divided into :
  • 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 role of constraints , Constraints can be divided into :
  • 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

1.4 View the existing constraints of a table

   among mysql Self contained information_schema.table_constraints A table is a constraint that stores individual tables .

#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

2.1 effect

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

2.2 keyword

NOT NULL

2.3 characteristic

  • Default , All types of values can be NULL, Include INT、FLOAT And so on
  • Non empty constraints can only appear on columns of table objects , Only one column can be qualified as 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.4 Add non empty constraints

1) Build table

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

2) Modify after creating a table

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

2.5 Delete non empty constraints

# Get rid of not null, It is equivalent to modifying a non annotation field , This field can be empty 
alter table  The name of the table  modify  Field name   data type  NULL;
 or 
# Get rid of not null, It is equivalent to modifying a non annotation field , This field can be empty 
alter table  The name of the table  modify  Field name   data type ;

3、 Uniqueness constraint

3.1 effect

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

3.2 keyword

UNIQUE

3.3 characteristic

  • The same table can have multiple unique constraints .
  • A unique constraint can be a unique value for a column , You can also combine multiple columns to have unique values .
  • The uniqueness constraint allows column values 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 index will be created by default for columns with unique constraints .

3.4 Add unique constraints

1) Add

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 
);
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 )
);

2) Specify the only key constraint after creating the table

# If it is a field in the field list , Indicates that the value of this column is unique .
# If there are two or more fields , So the compound is unique , That is, the combination of multiple fields is unique 
# 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;

3.5 Compound unique constraint

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, the combination of multiple fields is unique 
);

Take a chestnut : There is already a student list 、 The curriculum , When creating the course selection table , Students can be defined id And courses id Is a compound unique constraint , Because it is impossible for a student to choose the same course 2 Time , Then there's a problem . So you can add a compound unique constraint .

# 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,
  cid int,
  score int,
  unique key(sid,cid)  # Compound the only 
);

3.6 Delete unique constraint

  • Columns that add uniqueness constraints will also Automatically create unique indexes .
  • Delete unique constraint You can only delete by deleting a unique index .
  • You need to specify a unique index name when deleting , 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
    .

   First, you can use the table (information_schema.table_constraints) See what constraints are currently in place , Then delete the corresponding constraint according to the constraint name :

# See what constraints are 
SELECT * FROM information_schema.table_constraints WHERE table_name = ' Table name '; 

View indexes in tables :

show index from  The name of the table 

Delete USER Constraints in the table :

ALTER TABLE USER
DROP INDEX uk_name_pwd;

4、PRIMARY KEY constraint

4.1 effect

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

4.2 keyword

primary key

4.3 characteristic

  • A primary key constraint is equivalent to a unique constraint + A combination of nonnull constraints , Primary key constraint columns are not allowed to be duplicate , Null values are not allowed .
  • A table can have at most one primary key constraint , You can create a primary key constraint at the column level , You can also create... At the table level .
  • Primary key constraint Corresponding to one or more columns in the table ( Composite primary key )
  • MySQL The primary key name of is always PRIMARY, Even if you name the primary key constraint name, it's useless .
  • When When creating a primary key constraint , By default, the system will establish a corresponding primary key index on the column or column combination ( Can query according to the primary key
    Of , Just 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 the primary key is modified
    value , It may destroy the integrity of the data .

4.4 Add primary key constraint

1) Specify the primary key constraint when creating the table

create table  The name of the table (
  Field name   data type   primary key, # Column level mode 
   Field name   data type ,  
   Field name   data type   
);
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 
);

2) Add a primary key constraint after creating a table

# The field list can be a field , It can also be multiple fields , If there are multiple fields , The primary key is compound 
ALTER TABLE  The name of the table  ADD PRIMARY KEY( Field list ); 

4.5 Composite primary key

Just like adding a compound uniqueness constraint , You can also add a composite primary key :

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 
);

Or the student table 、 The curriculum 、 Take the course schedule as an example :

# Student list 
create table student(
 sid int primary key,  # Student number 
 sname varchar(20)     # The student's name 
);
# The curriculum 
create table course(
 cid int primary key,  # Course number 
 cname varchar(20)     # Course name 
);
# Course selection table 
create table student_course(
 sid int,
  cid int,
  score int,
  primary key(sid,cid)  # Composite primary key 
);

4.6 Delete primary key

   Delete primary key constraint , You do not need to specify the primary key name , Because a table has only one primary key , After deleting the primary key constraint , Non empty return
stay .

alter table  The name of the table  drop primary key;

5、 On the column :AUTO_INCREMENT

5.1 effect

The value of a field increases automatically .

5.2 keyword

auto_increment

5.3 characteristic

  • A table can only have at most one self growing column
  • When a unique identifier or sequential value needs to be generated , Self growth can be set
  • The column of the self growing column constraint must be a key column ( Primary key column , Unique key column )
  • The data type of a column with a self increasing constraint must be an integer type
  • If the auto increment column specifies 0 and null, It will automatically increase based on the current maximum ; If the auto increment column manually specifies a specific value , direct
    Assign a value to a specific value .

5.4 How to specify self increasing constraints

1) Build table

create table  The name of the table (
  Field name   data type   primary key auto_increment,
   Field name   data type   unique key not null,  
   Field name   data type   unique key,
   Field name   data type   not null default  The default value is ,
);
create table  The name of the table (
  Field name   data type  default  The default value is  ,
   Field name   data type  unique key auto_increment,  
   Field name   data type  not null default  The default value is ,,
  primary key( Field name )
);

2) After the establishment of the table

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

5.5 How to delete auto increment constraints

#alter table  The name of the table  modify  Field name   data type  auto_increment;# Add a self increasing constraint to this field 
alter table  The name of the table  modify  Field name   data type ; # Get rid of auto_increment It is equivalent to deleting 

5.6 MySQL 8.0 New characteristics — Persistence of self increasing variables

   stay MySQL 8.0 Before , Since the primary key AUTO_INCREMENT If the value of is greater than max(primary key)+1, stay MySQL After restart , Reset AUTO_INCREMENT=max(primary key)+1, In some cases, this phenomenon may lead to business primary key conflict or other difficult to find problems . That is to say 8.0 Before , If the database restarts ,mysql The latest self increasing value may not be the corresponding value that it should increase .
  MySQL 8.0 Persist the counter of self incrementing primary key to Redo log in . Every time the counter changes , Will be written to the redo log . If the database restarts ,InnoDB The memory value of the counter will be initialized according to the information in the redo log .

6、FOREIGN KEY constraint

6.1 effect

Limit the referential integrity of a field in a table .
such as : The selection of the employee's department in the employee table , The corresponding part must be found in the Department table .

6.2 keyword

FOREIGN KEY

6.3 characteristic

1) From the foreign key column of the table , Must quote / Columns that refer to the primary key or unique constraint of the main table
Why? ? Because of being dependent / The referenced value must be unique
2) When creating a foreign key constraint , If you don't name the foreign key constraint , The default name is not a column name , Instead, it automatically generates a foreign key name ( for example
student_ibfk_1;), You can also specify a foreign key constraint name .
3) establish (CREATE) If you specify a foreign key constraint when using the table , Create the main table first , Then create the slave table
4) When deleting a table , Delete from the table first ( Or delete the foreign key constraint first ), Delete the main table
5) When the records of the master table are referenced from the slave table , Records in the main table will not be allowed to be deleted , If you want to delete data , You need to delete the dependency from the table first
The recorded data , Then you can delete the data of the main table
.
6) stay “ From the table ” Specify foreign key constraints in , And a table can establish multiple foreign key constraints .
7) The foreign key column of the slave table and the column name of the main table can be different , But the data type must be the same , The logical meaning is consistent .
8) When creating a foreign key constraint , By default, the system will establish the corresponding common index on the column . But the index name is the constraint name of the foreign key .( It is very efficient to query according to foreign keys )
9) After deleting the foreign key constraint , must Manual Delete the corresponding index

6.3 Add a foreign key constraint

1) Build table

create table  Main table name (
  Field 1  data type   primary key,
  Field 2  data type 
);
create table  From table name (
  Field 1  data type    primary key,
   Field 2  data type , [CONSTRAINT < Foreign key constraint name >] FOREIGN KEY( From a field in the table ) references  Main table name ( Referenced field ));
#( From a field in the table ) The data type of must be the same as the main table name ( Referenced field ) The data types of are consistent , The logical meaning is the same 
#( From a field in the table ) The field name can be the same as the main table name ( Referenced field ) The field name of is the same , It can be different 
-- FOREIGN KEY:  Specify the columns in the child table at the table level 
-- REFERENCES:  Columns marked in the parent table 

2) After the establishment of the table
   In general , Table and table associations are designed in advance , therefore , The foreign key constraint will be defined when creating the table . however , If you need to modify the design of the table ( For example, add a new field , Add new relationships ), But there are no predefined foreign key constraints , that , We need to modify the table to supplement the definition .

ALTER TABLE  From the table name  
ADD [CONSTRAINT  Constraint name ] FOREIGN KEY ( From the fields of the table ) REFERENCES  Main table name ( Referenced fields ) [on update xx][on delete xx];

6.4 Constraint level

  • Cascade The way : On parent table update/delete When recording , Sync update/delete Drop matching records of child tables
  • Set null The way : On parent table update/delete When recording , Set the column of the matching record on the child table to null, But be careful
    The foreign key column of the table cannot be not null
  • No action The way : If there are matching records in the sub table , The parent table is not allowed to correspond to the candidate key update/delete operation
  • Restrict The way : Same as no action, Check foreign key constraints immediately
    If no level is specified , Equivalent to Restrict The way .
    For foreign key constraints , It's better to use : ON UPDATE CASCADE ON DELETE RESTRICT The way .
    Take a chestnut :
create table dept(
 did int primary key, # Department number 
 dname varchar(50) # Department name 
);
create table emp(
 eid int primary key,  # Employee number 
  ename varchar(5),     # Employee name 
  deptid int,
 # The employee's Department 
 foreign key (deptid) references dept(did)  on update cascade on delete set null
  # Set the modification operation to cascade modification level , Set the delete operation to set null Grade 
);

6.5 Delete foreign key constraint

1) The first step is to view the constraint name and delete the foreign key constraint

# View the constraint name of a table 
SELECT * FROM information_schema.table_constraints WHERE table_name = ' The name of the table ';
ALTER TABLE  From the table name  DROP FOREIGN KEY  Foreign key constraint name ;

2) The second step is to view the index name and delete the index .( Be careful , You can only manually delete )

SHOW INDEX FROM  The name of the table ; # View the index name of a table 
ALTER TABLE  From the table name  DROP INDEX  Index name ;

6.6 The actual use of foreign key constraints

problem : What is the difference between building and not building foreign key constraints ? If it's distributed 、 Whether the high concurrency cluster needs to add foreign keys

Foreign key constraint , Your operation ( Create table 、 Delete table 、 add to 、 modify 、 Delete ) Will be limited , Grammatically limited
system
. for example : It is impossible to add an employee information in the employee table , The value of its department cannot be found in the Department table .

No foreign key constraints , Your operation ( Create table 、 Delete table 、 add to 、 modify 、 Delete ) There is no limit on the , To ensure the accuracy of the data Reference integrity
sex
, Only by Rely on the programmer's consciousness , Or is it stay Java Define in the program . for example : In the employee list , You can add an employee's information , Its department is designated as a completely non-existent Department .

stay MySQL in , Foreign key constraints are costly , Need to consume system resources . about Large concurrent SQL operation , It may not be suitable for . For example, the central database of large websites , May be Because of the overhead of foreign key constraints . therefore , MySQL Allows you not to use the system's own foreign key constraints , stay Application level Complete the logic of checking data consistency . in other words , Even if you don't use foreign key constraints , We should also find ways to use additional logic at the application level , To implement the function of foreign key constraints , Ensure data consistency .

Ali Development Specification :
mandatory 】 Do not use foreign keys and cascades , All foreign key concepts must be solved in the application layer .

explain :( Conceptual explanation ) In the student list student_id It's the primary key , So the student_id Foreign key . If we learn to update
In the table student_id, Also trigger the student_id to update , That's cascading updates . Foreign keys and cascading updates apply to Single machine low concurrency , Not suitable for Distributed High concurrency cluster ; Cascading updates are strong blocking , There is a database Update storm The risk of ; Foreign keys affect the of the database Insertion speed .

7、CHECK constraint

7.1 effect

Check whether the value of a field is a symbol xx requirement , Generally refers to the range of values

7.2 keyword

CHECK

7.3 characteristic

MySQL5.7 have access to check constraint , but check Constraints have no effect on Data Validation . When adding data , There are no errors or warnings . however MySQL 8.0 Can be used in check Constrained .
Examples are as follows :

create table employee(
 eid int primary key,
  ename varchar(5),
  gender char check (' male ' or ' Woman ')
);
CREATE TABLE temp(
 id INT AUTO_INCREMENT,
 NAME VARCHAR(20),
 age INT CHECK(age > 20),
 PRIMARY KEY(id)
);

8、DEFAULT constraint

8.1 effect

Give a field / Specify a default value for a column , Once the default value is set , When inserting data , If this field has no explicit assignment , Then the assignment is default
Recognition .

8.2 keyword

DEFAULT

8.3 How to add the default value to the field

1) Build table
The default value constraint is generally not added to the unique key and primary key columns

create table  The name of the table (
  Field name   data type   primary key,
   Field name   data type   unique key not null,  
   Field name   data type   unique key,
   Field name   data type   not null default  The default value is ,
);
create table  The name of the table ( Field name   data type  default  The default value is  ,
   Field name   data type  not null default  The default value is ,  
   Field name   data type  not null default  The default value is ,
   primary key( Field name ),
   unique key( Field name )
);

2) After the establishment of the table

alter table  The name of the table  modify  Field name   data type  default  The default value is ;
# If this field had a non NULL constraint , You also keep non empty constraints , Then when adding the default value constraint , You have to keep the non NULL constraint , Otherwise, the non empty constraint will be deleted 
# Empathy , The same is true when you add a non NULL constraint to a field , If this field had a default value constraint , You want to keep , Also in modify Keep the default value constraint in the statement , Otherwise, it will be deleted 
alter table  The name of the table  modify  Field name   data type  default  The default value is  not null;

8.4 How to delete a default value constraint

alter table  The name of the table  modify  Field name   data type  ;# Delete default constraint , Non null constraints are not retained 
alter table  The name of the table  modify  Field name   data type   not null; # Delete default constraint , Keep non empty constraints 
原网站

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