Analysis of MySQL database constraints and table design examples
Database constraints
not null
Specify that the storage of a certain column cannot be a null value
create table student (id int not null,name varchar(20)); Query OK, 0 rows affected (0.01 sec) mysql> desc student; +-------+-------------+------+-----+---------+-------+ | Field | Type | Null | Key | Default | Extra | +-------+-------------+------+-----+---------+-------+ | id | int(11) | NO | | NULL | | | name | varchar(20) | YES | | NULL | | +-------+-------------+------+-----+---------+-------+ 2 rows in set (0.00 sec)
unique
Guarantee that a certain column must have a unique value , an error will be reported when inserting duplicate values
default
Specifies the default value when assigning values to columns
create table student(id int,name varchar(20) default '匿名');
primary key primary key
The primary key constraint is not The combination of null and unique ensures that the assignment of a column cannot be null and is unique
auto_increment Auto-increment features:
1. If there is no record in the table, the auto-increment starts from 1
2. If there is data, it will be incremented from the previous record.
3. Insert and then delete the data. The incremented value will not be reused and will start from the deleted one. Auto-increment
create table student (id int primary key auto_increment,name varchar(20)); Query OK, 0 rows affected (0.01 sec) mysql> desc student; +-------+-------------+------+-----+---------+----------------+ | Field | Type | Null | Key | Default | Extra | +-------+-------------+------+-----+---------+----------------+ | id | int(11) | NO | PRI | NULL | auto_increment | | name | varchar(20) | YES | | NULL | | +-------+-------------+------+-----+---------+----------------+ 2 rows in set (0.00 sec) mysql> insert into student values(null,'张三'); Query OK, 1 row affected (0.00 sec) mysql> select * from student; +----+--------+ | id | name | +----+--------+ | 1 | 张三 | +----+--------+ 1 row in set (0.00 sec)
foreign key foreign key
Foreign key constraints, the data in table one must exist in table two, refer to the integrity criteria
Foreign key constraints Describes the "dependency relationship" between two columns of two tables
Foreign key constraints will affect the deletion of the table. For example, the class table of the following example is associated, so it cannot be easily deleted
mysql> create table class ( -> id int primary key, -> name varchar(20) not null -> ); Query OK, 0 rows affected (0.04 sec) mysql> create table student ( -> id int primary key, -> name varchar(20) not null, -> email varchar(20) default 'unknow', -> QQ varchar(20) unique, -> classId int , foreign key (classId) references class(id) -> ); Query OK, 0 rows affected (0.03 sec) mysql> desc class; +-------+-------------+------+-----+---------+-------+ | Field | Type | Null | Key | Default | Extra | +-------+-------------+------+-----+---------+-------+ | id | int(11) | NO | PRI | NULL | | | name | varchar(20) | NO | | NULL | | +-------+-------------+------+-----+---------+-------+ 2 rows in set (0.02 sec) mysql> desc student; +---------+-------------+------+-----+---------+-------+ | Field | Type | Null | Key | Default | Extra | +---------+-------------+------+-----+---------+-------+ | id | int(11) | NO | PRI | NULL | | | name | varchar(20) | NO | | NULL | | | email | varchar(20) | YES | | unknow | | | QQ | varchar(20) | YES | UNI | NULL | | | classId | int(11) | YES | MUL | NULL | | +---------+-------------+------+-----+---------+-------+ 5 rows in set (0.00 sec)
check
Specify a condition and use the condition to determine the value
But mysql does not support
create table test_user ( id int, name varchar(20), sex varchar(1), check (sex ='男' or sex='女') );
table design
One-to-one
The one-to-one design table is like the student table and the account table. One account corresponds to one student, and each student has only one account
Expression method
1 .These two entities can be represented by one table
2. They can be represented by two tables, one of which contains the id of the other table
One-to-many
A student should be in a class, and a class can contain multiple students
Representation method:
1. In the class table, add a new column to represent the students in this class What are the student IDs (mysql does not have an array type, redis can)
2. The class table remains unchanged, and a new column of classId is added to the student table
many-to-many
Many-to-many design table is like a student table and a course schedule. A student can choose multiple courses, and a course can also be selected by multiple students.
Representation method:
Use a related table , to represent the relationship between two entities
Many-to-many table creation instance
-- 学生表 mysql> create table test_student ( -> id int primary key, -> name varchar(10) default 'unknow' -> ); Query OK, 0 rows affected (0.03 sec) -- 选课表 mysql> create table test_course ( -> id int primary key, -> name varchar(20) default 'unknow' -> ); Query OK, 0 rows affected (0.02 sec) -- 成绩表 mysql> create table test_score ( -> studentId int, -> courseId int, -> score int, -> foreign key (studentId) references test_student(id), -> foreign key (courseId) references test_course(id) -> ); Query OK, 0 rows affected (0.02 sec) mysql> desc test_student; +-------+-------------+------+-----+---------+-------+ | Field | Type | Null | Key | Default | Extra | +-------+-------------+------+-----+---------+-------+ | id | int(11) | NO | PRI | NULL | | | name | varchar(10) | YES | | unknow | | +-------+-------------+------+-----+---------+-------+ 2 rows in set (0.00 sec) mysql> desc test_coures; ERROR 1146 (42S02): Table 'java_5_27.test_coures' doesn't exist mysql> desc test_course; +-------+-------------+------+-----+---------+-------+ | Field | Type | Null | Key | Default | Extra | +-------+-------------+------+-----+---------+-------+ | id | int(11) | NO | PRI | NULL | | | name | varchar(20) | YES | | unknow | | +-------+-------------+------+-----+---------+-------+ 2 rows in set (0.00 sec) mysql> desc test_score; +-----------+---------+------+-----+---------+-------+ | Field | Type | Null | Key | Default | Extra | +-----------+---------+------+-----+---------+-------+ | studentId | int(11) | YES | MUL | NULL | | | courseId | int(11) | YES | MUL | NULL | | | score | int(11) | YES | | NULL | | +-----------+---------+------+-----+---------+-------+ 3 rows in set (0.00 sec)
Insert data into the instance to implement many-to-many
mysql> insert into test_student values (1, 'listen'); Query OK, 1 row affected (0.01 sec) mysql> insert into test_course values (1, '数学'); Query OK, 1 row affected (0.00 sec) mysql> insert into test_student values (2, 'Faker'); Query OK, 1 row affected (0.00 sec) mysql> insert into test_course values (2, '数学'); Query OK, 1 row affected (0.00 sec) mysql> insert into test_score values(1, 1, 90); Query OK, 1 row affected (0.00 sec) mysql> insert into test_score values (1, 2, 99); Query OK, 1 row affected (0.00 sec) mysql> insert into test_score values (2, 1, 50); Query OK, 1 row affected (0.00 sec) mysql> insert into test_score values (2, 2, 60); Query OK, 1 row affected (0.00 sec) mysql> select * from test_student; +----+--------+ | id | name | +----+--------+ | 1 | listen | | 2 | Faker | +----+--------+ 2 rows in set (0.00 sec) mysql> select * from test_course; +----+--------+ | id | name | +----+--------+ | 1 | 数学 | | 2 | 语文 | +----+--------+ 2 rows in set (0.00 sec) mysql> select * from test_score; +-----------+----------+-------+ | studentId | courseId | score | +-----------+----------+-------+ | 1 | 1 | 90 | | 1 | 2 | 99 | | 2 | 1 | 50 | | 2 | 2 | 60 | +-----------+----------+-------+ 4 rows in set (0.00 sec)
The above is the detailed content of Analysis of MySQL database constraints and table design examples. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics











Laravel is a PHP framework for easy building of web applications. It provides a range of powerful features including: Installation: Install the Laravel CLI globally with Composer and create applications in the project directory. Routing: Define the relationship between the URL and the handler in routes/web.php. View: Create a view in resources/views to render the application's interface. Database Integration: Provides out-of-the-box integration with databases such as MySQL and uses migration to create and modify tables. Model and Controller: The model represents the database entity and the controller processes HTTP requests.

MySQL and phpMyAdmin are powerful database management tools. 1) MySQL is used to create databases and tables, and to execute DML and SQL queries. 2) phpMyAdmin provides an intuitive interface for database management, table structure management, data operations and user permission management.

Compared with other programming languages, MySQL is mainly used to store and manage data, while other languages such as Python, Java, and C are used for logical processing and application development. MySQL is known for its high performance, scalability and cross-platform support, suitable for data management needs, while other languages have advantages in their respective fields such as data analytics, enterprise applications, and system programming.

I encountered a tricky problem when developing a small application: the need to quickly integrate a lightweight database operation library. After trying multiple libraries, I found that they either have too much functionality or are not very compatible. Eventually, I found minii/db, a simplified version based on Yii2 that solved my problem perfectly.

Article summary: This article provides detailed step-by-step instructions to guide readers on how to easily install the Laravel framework. Laravel is a powerful PHP framework that speeds up the development process of web applications. This tutorial covers the installation process from system requirements to configuring databases and setting up routing. By following these steps, readers can quickly and efficiently lay a solid foundation for their Laravel project.

When developing an e-commerce website using Thelia, I encountered a tricky problem: MySQL mode is not set properly, causing some features to not function properly. After some exploration, I found a module called TheliaMySQLModesChecker, which is able to automatically fix the MySQL pattern required by Thelia, completely solving my troubles.

MySQL efficiently manages structured data through table structure and SQL query, and implements inter-table relationships through foreign keys. 1. Define the data format and type when creating a table. 2. Use foreign keys to establish relationships between tables. 3. Improve performance through indexing and query optimization. 4. Regularly backup and monitor databases to ensure data security and performance optimization.

MySQL is an open source relational database management system that is widely used in Web development. Its key features include: 1. Supports multiple storage engines, such as InnoDB and MyISAM, suitable for different scenarios; 2. Provides master-slave replication functions to facilitate load balancing and data backup; 3. Improve query efficiency through query optimization and index use.
