How to set constraints on tables in MySQL database
1. PK (primary key constraint)
1. What is a primary key?
Before understanding the primary key, first understand what a keyword is
Keyword: a unique field in the table, such as a A person’s ID number and student number. There can be multiple keywords in a table.
The primary key is a combination of one or more keywords. Information about the entire table can be obtained through the primary key. It is sometimes also called the primary key. Taking the order table as an example, you can obtain the order's consignee name, product information, price and other related information through the order number.
Note: The keyword does not have to be the primary key, the primary key must be the keyword
Features: The primary key cannot be empty, is unique and cannot be repeated. A table either has only one primary key or no primary key, and cannot have multiple primary keys.
2. How to set the primary key?
Method 1: Set the primary key when creating the table
-- 建立User表 CREATE TABLE User( User_id int NOT NULL, User_name VARCHAR(20), User_pwd VARCHAR(18), -- 在这里设置id为主键 PRIMARY KEY(User_id) )
CREATE TABLE Users( -- 也可以在字段中直接设置主键 User_id int NOT NULL PRIMARY KEY, User_name VARCHAR(20), User_pwd VARCHAR(18) )
Both of the above methods can create a primary key with the same effect.
Method 2: No primary key is set when creating the table, and then set the primary key in the table
First create a table without setting the primary key
CREATE TABLE User( User_id int NOT NULL, User_name VARCHAR(20), User_pwd VARCHAR(18) )
Then set the primary key
The principle is to add PRIMARY KEY (User_id) to the code when creating the table
Follow the method in method one The first principle is the same
ALTER TABLE user ADD PRIMARY KEY(User_id)
The principle is to add PRIMARY KEY to the User_id field
The same as the second principle in method one
ALTER TABLE users MODIFY User_id INT PRIMARY KEY;
2. FK (foreign key constraint)
1. What is a foreign key?
Foreign keys are also called foreign keywords and represent the direct connection between two tables. The foreign key of one table must be the primary key of another table. The table with the foreign key of another relationship as the primary key is called the master table, and the table with the foreign key is called the slave table of the master table.
For example, the order table contains two foreign keys: product ID and user ID. The product ID is the primary key of the product information table, and the user ID is the primary key of the user table.
Note: There can be multiple or no foreign keys in a table.
2. How to set foreign keys
Method 1: Set foreign key constraints when creating a table
Let’s take an example based on the previous setting of the primary key. We created a user table earlier. So now create an orders table.
CREATE TABLE dingdan( DDid INT PRIMARY KEY NOT NULL, User_id INT NOT null, DDname VARCHAR(20) NOT NULL, -- 设置约束关系,dingdan表中的User_id 与 user表中的User_id表示的是同一个数据 constraint fk FOREIGN KEY(User_id) REFERENCES user(User_id) )
Method 2: The primary key is not set when creating the table, and the primary key is set in the table later
alter table student add constraint stfk foreign key(stid) references teacher(tid)
Note: After the primary and foreign key relationships are established, the data in the main table cannot be deleted at will. If a user's information is included in the order data, an error will occur when deleting the user's information, so the user's information needs to be retained.
3. unique (unique constraint)
1. What is a unique constraint?
If a unique constraint is set on a field, then the field must either not be written, or if written, it cannot be repeated.
2. How to set unique constraints
Still create a user table, this time there is an email field in the table. Setting the email cannot be repeated
CREATE TABLE User( User_id int NOT NULL, User_name VARCHAR(20), User_pwd VARCHAR(18), User_Email VARCHAR(40) UNIQUE )
4. not null (not empty)
means that this field cannot be empty
Follow the above unique constraint to write, here it is stipulated that not only the email cannot be empty Repeat and cannot be empty
CREATE TABLE User( User_id int NOT NULL, User_name VARCHAR(20), User_pwd VARCHAR(18), User_Email VARCHAR(40) UNIQUE not null )
5. default (default value)
means that if you don’t write this field, you will be given a value by default and continue to write in the User table above. Add a gender field here. If you don’t write gender, the default is male
CREATE TABLE User( User_id int NOT NULL, User_name VARCHAR(20), User_pwd VARCHAR(18), User_gender enum('男','女') default '男' )
6. auto_increment (self-increment)
Auto-increment means automatic increment, that is to say, if you don’t have any in this field Fill in the data, and the system will automatically add 1
based on the previous data. Generally used in ID, the number
sets the ID in the user table to auto-increment
CREATE TABLE User( User_id int auto_increment, User_name VARCHAR(20), User_pwd VARCHAR(18), User_gender enum('男','女') default '男' )
Note: No. If a piece of data is not filled in, a value will be given by default. So even if the ID is the primary key, you don’t need to fill in the data
The above is the detailed content of How to set constraints on tables in MySQL database. 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

MySQL is an open source relational database management system, mainly used to store and retrieve data quickly and reliably. Its working principle includes client requests, query resolution, execution of queries and return results. Examples of usage include creating tables, inserting and querying data, and advanced features such as JOIN operations. Common errors involve SQL syntax, data types, and permissions, and optimization suggestions include the use of indexes, optimized queries, and partitioning of tables.

You can open phpMyAdmin through the following steps: 1. Log in to the website control panel; 2. Find and click the phpMyAdmin icon; 3. Enter MySQL credentials; 4. Click "Login".

MySQL is chosen for its performance, reliability, ease of use, and community support. 1.MySQL provides efficient data storage and retrieval functions, supporting multiple data types and advanced query operations. 2. Adopt client-server architecture and multiple storage engines to support transaction and query optimization. 3. Easy to use, supports a variety of operating systems and programming languages. 4. Have strong community support and provide rich resources and solutions.

MySQL's position in databases and programming is very important. It is an open source relational database management system that is widely used in various application scenarios. 1) MySQL provides efficient data storage, organization and retrieval functions, supporting Web, mobile and enterprise-level systems. 2) It uses a client-server architecture, supports multiple storage engines and index optimization. 3) Basic usages include creating tables and inserting data, and advanced usages involve multi-table JOINs and complex queries. 4) Frequently asked questions such as SQL syntax errors and performance issues can be debugged through the EXPLAIN command and slow query log. 5) Performance optimization methods include rational use of indexes, optimized query and use of caches. Best practices include using transactions and PreparedStatemen

Apache connects to a database requires the following steps: Install the database driver. Configure the web.xml file to create a connection pool. Create a JDBC data source and specify the connection settings. Use the JDBC API to access the database from Java code, including getting connections, creating statements, binding parameters, executing queries or updates, and processing results.

The process of starting MySQL in Docker consists of the following steps: Pull the MySQL image to create and start the container, set the root user password, and map the port verification connection Create the database and the user grants all permissions to the database

The main role of MySQL in web applications is to store and manage data. 1.MySQL efficiently processes user information, product catalogs, transaction records and other data. 2. Through SQL query, developers can extract information from the database to generate dynamic content. 3.MySQL works based on the client-server model to ensure acceptable query speed.

The key to installing MySQL elegantly is to add the official MySQL repository. The specific steps are as follows: Download the MySQL official GPG key to prevent phishing attacks. Add MySQL repository file: rpm -Uvh https://dev.mysql.com/get/mysql80-community-release-el7-3.noarch.rpm Update yum repository cache: yum update installation MySQL: yum install mysql-server startup MySQL service: systemctl start mysqld set up booting
