[⑪MySQL | Constraint (1)] concept | non-null | unique | primary key | self-growth constraint

foreword

✨Welcome to Xiao K 's MySQL column , this section will bring you the concept of MySQL constraints | non-null constraints | unique constraints | primary key constraints | sharing of self-growth constraints


1. Constraint concept

1.1 Why constraints are needed

For the created table, although the data type of the field determines the type of data that can be stored, the legality of the data stored in the table is not checked. When using the MySQL software, if you want to do some integrity check operations on the data in the table, you can do it through the constraints of the table.

Data integrity ( Data Intergrity) refers to the accuracy ( Accuracy) and reliability ( Reliability) of data. It is proposed to prevent the existence of data that does not meet the semantic requirements in the database and to prevent invalid operations or error information caused by the input and output of error information.

In order to ensure the integrity of the data, the SQL specification imposes additional conditional restrictions on the table data in a constrained manner , mainly from the following four aspects:

  • Entity Integrity (Entity Integrity): In the same table, there cannot be two identical and indistinguishable records
  • Domain Integrity (Domain Integrity) such as: age range 0-120, gender range "male/female"
  • Referential Integrity (Referential Integrity): For example, the employee's department must exist in the department table
  • User-defined integrity (User-defined Integrity) such as: unique username, password cannot be empty, etc.

1.2 What is a constraint

Constraints are table-level enforcements.

Constraints can be specified at table creation time (via the ``CREATE TABLE 语句),或者在表创建之后通过ALTER TABLE` statement.

1.3 Constraint Classification

1.3.1 Field classification according to constraints

  • single column constraint
  • multi-column constraints

1.3.2 Classification according to the scope of constraints

  • column-level constraints
  • table-level constraints

the difference

① The position is different: the column-level constraints are written after the columns, and when the constraints are marked, they are written at the end of all fields

② Supported constraint types are different: column-level constraints can support all constraint types, table-level constraints cannot support non-null and default

③ Column-level constraints cannot be given a constraint name, but table constraints can be given a constraint name (except for the primary key, which uses the PRIMARY KEY)

1.3.3 Classification according to the role of constraints

Integrity Constraint Keyword illustrate
NOT NULL(NK) The value of the constraint field cannot be empty
DEFAULT Set the default value for a field
UNIQUE KEY(UK) The value of the constraint field is unique (the same value cannot appear in the same column)
PRIMARAY KEY(PK) The constraint field is the primary key of the table, which can be used as the unique identifier of the table record
AUTO_INCREMENT The value of the constraint field is automatically incremented
FOREIGN KEY(FK) The constrained field is the foreign key of the table
CHECK()
  • View existing constraints on a table

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

2. Not Null Constraint (NK)

2.1 Concept

When the content of a field in the database table does not want to be set to NULL, you can use the NK constraint to set it. That is, the NK constraint adds a "NOT NULL" constraint condition to certain fields when creating a database table to ensure that the field has a value in all records. If the field is empty in the record inserted by the user, the database management system will report an error.

2.2 Features

  • By default, values ​​of all types can be NULL
  • A table can have many fields specifying not-null constraints
  • The empty string " " is not equal to NULL, 0 is not equal to NULL, and NULL is not equal to NULL

2.3 Adding a non-null constraint

  1. when creating the table
CREATE TABLE table_name(
	字段名 数据类型 NOT NULL,
    ...
);
CREATE TABLE IF NOT EXISTS student
(
	id INT NOT NULL,
	name VARCHAR(10) NOT NULL,
	score DECIMAL(4,1)
)
DESC student;

insert image description here

Tips1 : If we execute the following statement now, an error will be reported (Field 'name' doesn't have a default value)
, this is because the default value is NULL, and we have specified that the field cannot be empty

INSERT INTO student(id,score) VALUES(3,79.5);

  1. Add after creation
ALTER TABLE <表名> MODIFY 字段名 数据类型 约束;

Tips2 : If we execute the following statement now, an error (Invalid use of NULL value) will be reported, because there is scorealready a null value in the field

ALTER TABLE student MODIFY score DECIMAL(4,1) NOT NULL;

2.4 Delete the non-null constraint

ALTER TABLE 表名 MODIFY 字段名 数据类型 NULL;
#或
ALTER TABLE 表名 MODIFY 字段名 数据类型;

3. Unique constraints (UK)

3.1 Concept

When the content of a certain field in the database table is not allowed to be repeated, you can use the UK constraint to set it. That is, the UK constraint adds "UNIQUE" constraints to certain fields when creating a database table to ensure that the values ​​​​on this field in all records are not repeated. If the value of the field in the record inserted by the user is the same as the value of the field in other records, the database management system will report an error.

3.2 Features

  • The same table can have multiple unique constraints
  • The unique constraint allows a value of NULL
  • When creating a unique constraint, if you do not name the unique constraint, the constraint name is the same as the field name

3.3 Add unique constraints

  1. When creating the table add
CREATE TABLE table_name(
	字段名 数据类型 UNIQUE KEY,
    ...
);
  1. After creating the table add
  • method one
ALTER TABLE <表名> MODIFY 字段名 数据类型 UNIQUE;
  • Method Two
ALTER TABLE <表名> ADD [CONSTRAINT 约束名] UNIQUE [KEY](字段名);

3.4 Delete the unique constraint

  • A unique index is automatically created on the column where the unique constraint is added
  • Deleting a unique constraint can only be deleted by deleting the unique index
  • When deleting, you need to specify a unique index name, which is the same as the unique constraint name.
  • If no name is specified when creating a unique constraint, if it is a single column, it will be the same as the column name by default; if it is a combined column, the default will be the same as the first column name in ().
ALTER TABLE <表名> DROP INDEX <索引名>;

4. Primary key constraint (PK)

4.1 Concept

When you want to use a field in the database table to uniquely identify all records, you can use the PK constraint to set it. That is, the PK constraint adds a "PRIMARY KEY" constraint to some fields when creating a database table, and this field can uniquely mark all records.

The reason why the primary key is set in the database table is to facilitate the database management system to quickly find the records in the table. When specifically setting the primary key constraint, it must be satisfied that the value of the primary key field is unique and non-empty. Since the primary key can be a single field or multiple fields, it is divided into single-field primary key and multi-field primary key.

4.2 Features

  • The primary key constraint is equivalent to the unique constraint + not-null constraint , which means that duplicate and NULL values ​​are not allowed

  • The primary key constraint corresponds to one or more columns in the table (composite primary key)

  • If it is a composite primary key constraint composed of multiple columns, these columns are not allowed to be NULL values, and the combined values ​​​​do not allow duplicates

  • MySQL's primary key name is always PRIMARY, even if you name the primary key constraint name yourself, it is useless

  • When creating a primary key constraint, the system will create a corresponding primary key index on the column or combination by default (if it can be queried based on the primary key, it can be queried based on the primary key, which is more efficient). If the primary key constraint is deleted, the index corresponding to the primary key constraint will be 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 identifier of the data record, if the value of the primary key is modified, the integrity of the data may be destroyed.

4.3 Single field primary key

  • Specify primary key constraints when creating tables
CREATE TABLE table_name(
	字段名 数据类型  PRIMARY KEY,
    ...
);

Tips : If we execute the following statement now, an error will be reported (Multiple primary key defined)

CREATE TABLE IF NOT EXISTS test2
(
	empno INT PRIMARY KEY,   # 列级约束
	ename VARCHAR(10) PRIMARY KEY,
	sal DECIMAL(7,1)
)

Only one allowed! ! !

  • ALTER TABLE adds primary key constraints
ALTER TABLE <表名> ADD PRIMARY KEY(字段名);

4.4 Multi-field primary key (composite primary key)

When the primary key is composed of multiple fields, it needs to CONSTRAINTbe implemented through SQL statements, and the syntax is as follows:

CREATE TABLE table_name(
	字段名 数据类型,
    ...
    [CONSTRAINT 约束名] PRIMARY KEY(字段1,字段2...)
);

In the above statement, the primary key is uniformly set after the fields are defined. There can be multiple fields in the parentheses of the PRIMARY KEY keyword, which need to be separated by commas to realize the setting of multi-field primary keys.

4.5 Delete the primary key

ALTER TABLE <表名> DROP PRIMARY KEY;

5. Set the field value to automatically increase (AUTO_INCREMENT)

5.1 Concept

AUTO_INCREMENT is the only extended integrity constraint in MySQL. When a new record is inserted into a database table, the value on the field will automatically generate a unique ID. When specifically setting the AUTO_INCREMENT constraint, only one field in a database table can use this constraint, and the data type of this field must be an integer type. Since the field after setting the AUTO_INCREMENT constraint will generate a unique ID, this field is often set as the PK primary key.

5.2 Features

  • A table can have at most one self-increasing column
  • When a unique identifier or sequence value needs to be generated, self-growth can be set
  • The column constrained by the self-growth column must be a key column (primary key column, unique key column)
  • The data type of the column of the self-increment constraint must be an integer type
  • If the auto-increment column specifies 0 or NULL, it will auto-increment based on the current maximum value; if the auto-increment column specifies a specific value manually, directly pay Zhiwei the specific value.

5.3 Specifying Incremental Constraints

  1. Method 1: Creating a table is to specify
CREATE TABLE table_name(
	字段名 数据类型 PRIMARY KEY|UNIQUE AUTO_INCREMENT,
    ...
);
  1. Method 2: Add via ALTER TABLE
ALTER TABLE <表名> MODIFY 字段名 数据类型 AUTO_INCREMENT;

5.4 Delete auto-increment constraints

ALTER TABLE <表名> MODIFY 字段名 数据类型;

TIPS: As shown in the figure below, delete the data with empno equal to 3, and then insert a piece of data, empno is not 3 but 4

insert image description here

6. Summarize the gift book + how to learn machine learning? : The new PyTorch version of one of the "Four Great Masterpieces" of Python deep learning

#直播解决[7:30 tonight] How to learn machine learning? About the road to industrial practice of machine learning, as well as large-scale model technology and product insights, just tonight #video number: IT reading list
insert image description here

✨✨✨✨✨✨✨✨✨✨✨✨✨✨✨✨In
recent years, machine learning methods have been widely used in industries such as healthcare, robotics, biology, physics, mass consumption, and Internet services due to their ability to understand massive amounts of data and make autonomous decisions.
The positioning of the book "Python Machine Learning: Based on PyTorch and Scikit-Learn" is to combine machine learning theory with engineering practice, thereby lowering the reading threshold for readers. From the fundamentals of data-driven methods to the latest deep learning frameworks, each chapter of this book provides machine learning code examples for solving practical machine learning problems.

insert image description here

This is a comprehensive guide to learning machine learning and deep learning in the PyTorch environment. It can be used as an introductory tutorial for beginners, or as a reference book for readers when developing machine learning projects.
Provides an in-depth introduction to the fundamentals of machine learning methods, providing not only instructions for building machine learning models, but also basic guidelines for building machine learning models and solving practical problems. Whether you are new to machine learning or plan to track the progress of machine learning, this book can be used as the best choice for machine learning with Python.

Interested friends can read and buy by themselves.
Dangdang.com purchase link: The new PyTorch version of one of the "Four Great Masterpieces" of Python deep learning

✨✨Two books will be given away this time, and two friends will be selected in the comment area to send books✨✨Activity
time: until 2023-07-22 20:00:00,
the winning friends can choose one of the above 2 books.
How to draw : use the program to draw.
Participation methods : follow bloggers, like, bookmark, and post high-quality comments in the comment area (a single account can comment up to three times)

Guess you like

Origin blog.csdn.net/qq_72157449/article/details/131812634