Table of Contents
constraints
4. foreign key(外键约束)
5. 级联更新与级联删除
Home Database Mysql Tutorial What are the conditions when MySQL creates a table?

What are the conditions when MySQL creates a table?

Jun 03, 2023 pm 06:55 PM
mysql

Due to the addition, deletion and modification of records in the emp table, a script is re-created here and used

create database bjpowernnode;
use bjpowernode;
source C:\Users\Administrator\Desktop\bjpowernode.sql;
Copy after login

constraints

1. What are constraints?

  • Constraints are the restrictions in the table

  • The keyword of the constraint is: constraint

2. Classification of constraints

  • Non-null constraint not null

  • Unique Sexual constraints unique

  • Primary key constraints primary key

  • ##Foreign key constraints

    foreign key

  • Checking constraints MySQL database does not support it, Oracle database supports it

1. not null (non-null constraint)

The fields with not null constraints cannot be null values. Specific data must be created.

Create a table and add non-null constraints to the fields [The user’s email address cannot be null]

drop table if exists t_user;
create table t_user(
        id int(10),
        name varchar(32) not null,
        email varchar (32)
);
Copy after login

What are the conditions when MySQL creates a table?

What are the conditions when MySQL creates a table?

2. unique (unique constraint)

Create a table to ensure that the email address is unique

create table t_user(
id int(10),
name varchar(32) not null,
email varchar(128) unique
);
Copy after login

What are the conditions when MySQL creates a table?

The fields of unique constraints cannot be repeated, but can be null

What are the conditions when MySQL creates a table?

The above constraints are column-level constraints

Table-level constraints:

 create table t_user(
     id int(10),
     name varchar(32),
     email varchar(128),
     unique(email)
 );
Copy after login

1. Use table-level constraints to add constraints to multiple fields

 create table t_user(
     id int(10),
     name varchar(32),
     email varchar(128),
     unique(name,email)
);
Copy after login

2. Table-level constraints can give the constraint a name, and later delete the constraint through this name

   create table t_user(
       id int(10),
       name varchar(32),
       email varchar(128),
       constraint t_user_email_unique unique(email)
 );
Copy after login

What are the conditions when MySQL creates a table?

What are the conditions when MySQL creates a table?

What are the conditions when MySQL creates a table?##not null and unique can be used together

What are the conditions when MySQL creates a table?3. primary key (primary key constraint)

1. Terms related to primary key:

    Primary key constraint
  • Primary key field
  • Primary key value
  • ##2. The relationship between the above three:

After adding a primary key constraint to a field in the table, the field is called the primary key field
  • Each occurrence in the primary key field The data are all called primary key values
  • 3. After adding a primary key constraint to a field, the field cannot be repeated or empty

The primary key constraint has the same effect as ''not null unique'', but the essence is different.
  • Primary key constraint can also achieve ''not null unique'' In addition to
  • the primary key field will also be added with ''index-index'' by default
  • 4. A table should have Primary key field, if not, it means that this table is invalid

The primary key value is the unique identifier of the current row of data
  • The primary key value is the ID number of the current row of data
  • Even if the two rows of record data in the table are exactly the same,
  • But because If the primary key values ​​are different, they are considered to be two completely different fields in the two rows
  • 5. Whether it is a single primary key or a composite primary key, a table can only have one primary key constraint.

Adding a primary key constraint to a field is called a single primary key constraint
  • Adding a primary key constraint to multiple fields jointly is called a single primary key constraint It is called a composite primary key
  • 6. Primary keys are classified according to their properties:

Natural primary key: The primary key value is a natural number , this primary key has nothing to do with the current business
  • Business primary key: The primary key value is closely related to the current business
  • When the business changes , the primary key value will always be affected, so the business primary key is of little use.
  • Single primary key, column-level constraints
  • create table t_user(
        id int(10) primary key,
        name varchar(32)
    );
    Copy after login

Single primary key, table-level constraintsWhat are the conditions when MySQL creates a table?

 create table t_user(
     id int(10),
     name varchar(32),
     primary key(id)
);
Copy after login

Composite primary key: only table-level constraints can be usedWhat are the conditions when MySQL creates a table?

mysql> create table t_user(
    -> id int(10),
    -> name varchar(32),
    -> primary key(id,name)
    -> );
Copy after login

What are the conditions when MySQL creates a table?

auto_increment:主键自增

MySQL数据管理系统中提供了一个自增的数字,专门用来自动生成主键值

主键值不需要用户维护,也不需要用户提供了,自动生成的,

这个自增的数字默认从1开始以1递增:1,2,3,4,....

mysql> create table t_user(
    -> id int(10) primary key auto_increment,
    -> name varchar(32)
    -> );
Copy after login

What are the conditions when MySQL creates a table?

4. foreign key(外键约束)

1.外键约束涉及到的术语:

  • 外键约束

  • 外键值

  • 外键字段

2.以上三者之间的关系:

  • 某个字段添加外键约束以后称为外键字段

  • 外键字段中的每一个数据称为外键值

3.外键分为单一外键和复合外键

  • 单一外键:给一个字段添加外键约束

  • 复合外键:给多个字段添加外键约束

4.一张表中可以有多个外键字段

设计一个数据库表,用来存储学生和班级信息,给出两种解决方案:

学生信息和班级信息之间的关系:一个班级对应多个学生,这是典型的一对多的关系

在多的一方加外键

第一种设计方案:将学生信息和班级信息存储到一张表中

第二种设计方案:将学生信息和班级信息分开两张表存储,学生表+班级表

  • 学生表 t_student

sno(主键约束)snameclassno(外键约束)
1jack100
2lucy100
3kk100
4smith200
5frank300
6jhh300
  • 班级表t_calss

cno(主键约束)cname
100高三1班
200高三2班
300高三3班

为了保证t_student 表中的classno字段中的数据必须来自于t_class表中的cno字段中的数据,有必要给t_student表中的classno字段添加外键约束,classno称为外键字段,该字段中的值称为外键值。

注意:

1.外键值可以为空

2.外键字段必须得引用这张表中的主键吗?

  • 外键字段引用一张表的字段的时候,被引用的字段必须具备唯一性

  • 即具有unique约束,不一定非是主键

3.班级表为父表,学生表为子表

  • 应该先创建父表,再创建子表

  • 删除数据时,应该先删除子表中的数据,再删除父表中的数据

  • 插入数据时,应该先插入父表中的数据,再删除子表中的数据

What are the conditions when MySQL creates a table?

DROP TABLE IF EXISTS t_student;
DROP TABLE IF EXISTS t_class;
 
 CREATE TABLE t_class(
 cno INT(3) PRIMARY KEY,
 cname VARCHAR(128) NOT NULL UNIQUE
 );
 
 CREATE TABLE t_student(
 sno INT(3) PRIMARY KEY,
 sname VARCHAR(32) NOT NULL,
 classno INT(3),-- 外键
 CONSTRAINT t_student_class_fk FOREIGN KEY(classno) REFERENCES t_class(cno)
 );
 
 INSERT INTO t_class(cno,cname) VALUES(100,'高三1班');
 INSERT INTO t_class(cno,cname) VALUES(200,'高三2班');
 INSERT INTO t_class(cno,cname) VALUES(300,'高三3班');
 
 INSERT INTO t_student(sno,sname,classno) VALUES(1,'jack',100);
 INSERT INTO t_student(sno,sname,classno) VALUES(2,'lucy',100);
 INSERT INTO t_student(sno,sname,classno) VALUES(3,'hh',100);
 INSERT INTO t_student(sno,sname,classno) VALUES(4,'frank',200); 
 INSERT INTO t_student(sno,sname,classno) VALUES(5,'smith',300);
 INSERT INTO t_student(sno,sname,classno) VALUES(6,'jhh',300);
 
 SELECT * FROM t_student;
 SELECT * FROM t_class;
 
-- 添加失败,因为有外键约束 
 INSERT INTO t_student(sno,sname,classno) VALUES(8,'kk',500);
Copy after login

重点:典型的一对多关系,设计时在多的一方加外键

5. 级联更新与级联删除

在删除父表中的数据的时候,级联删除子表中的数据

在更新父表中的数据的时候,级联更新子表中的数据

以上的级联更新和级联删除谨慎使用,

因为级联操作会使数据数据改变或删除,数据是无价的。

语法:

  • 级联更新:on update cascase

  • 级联删除:on delete cascase

What are the conditions when MySQL creates a table?

What are the conditions when MySQL creates a table?

MySQL中对于有些约束的修改比较麻烦,所以应该先删除约束,再添加约束

删除外键约束:

alter table t_student drop foreign key t_student_class_fk
Copy after login

添加外键约束并级联更新:

alter table t_student add constraint t_student_class_fk foreign key(classno)
references t_class(no) on delete cascade;
Copy after login

添加外键约束并级联删除:

alter table t_student add constraint t_student_class_fk foreign key(classno)
references t_class(no) on update cascade;
Copy after login

级联删除

What are the conditions when MySQL creates a table?

What are the conditions when MySQL creates a table?

级联更新

What are the conditions when MySQL creates a table?

What are the conditions when MySQL creates a table?

The above is the detailed content of What are the conditions when MySQL creates a table?. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1664
14
PHP Tutorial
1269
29
C# Tutorial
1249
24
Laravel Introduction Example Laravel Introduction Example Apr 18, 2025 pm 12:45 PM

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: Core Features and Functions MySQL and phpMyAdmin: Core Features and Functions Apr 22, 2025 am 12:12 AM

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.

MySQL vs. Other Programming Languages: A Comparison MySQL vs. Other Programming Languages: A Comparison Apr 19, 2025 am 12:22 AM

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.

Solve database connection problem: a practical case of using minii/db library Solve database connection problem: a practical case of using minii/db library Apr 18, 2025 am 07:09 AM

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.

Laravel framework installation method Laravel framework installation method Apr 18, 2025 pm 12:54 PM

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.

Solve MySQL mode problem: The experience of using the TheliaMySQLModesChecker module Solve MySQL mode problem: The experience of using the TheliaMySQLModesChecker module Apr 18, 2025 am 08:42 AM

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: Structured Data and Relational Databases MySQL: Structured Data and Relational Databases Apr 18, 2025 am 12:22 AM

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: Key Features and Capabilities Explained MySQL: Key Features and Capabilities Explained Apr 18, 2025 am 12:17 AM

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.

See all articles