Table of Contents
1. 约束
2. 外键约束的参照操作
3. 表级约束与列级约束
4. 修改数据表
Home Database Mysql Tutorial 【MySQL】(3)约束以及修改数据表_MySQL

【MySQL】(3)约束以及修改数据表_MySQL

Jun 01, 2016 pm 12:59 PM
data sheet

1. 约束

约束保证数据的完整性和一致性,约束分为表级约束和列级约束。约束类型包括:NOT NULL(非空约束)、PRIMARY KEY(主键约束)、UNIQUE KEY(唯一约束)、DEFAULT(默认约束)、FOREIGN KEY(外检约束)。

外键约束保证了数据的一致性、完整性,实现了一对一或一对多的关系

外键约束的要求:

(1). 父表和字表必须使用相同的存储引擎,而且禁止使用临时表。

(2). 数据表的存储引擎只能为InnoDB。

(3). 外键列和参照列必须具有相似的数据类型。其中数字的长度或是否有符号位必须相同;而字符的长度则可以不同。

(4). 外键列和参照列必须创建索引。如果外键列不存在索引的话,MySQL将自动创建索引。

MySQL配置文件:

default-storage-engine=INNODB

 

CREATE TABLE provinces(id SMALLINT UNSIGNED PRIMARY KEY AUTO_INCREMENT, pname VARCHAR(20) NOT NULL);
SHOW CREATE TABLE provinces;
CREATE TABLE users(id SMALLINT UNSIGNED PRIMARY KEY AUTO_INCREMENT, username VARCHAR(10) NOT NULL, pid SMALLINT UNSIGNED, FOREIGN KEY(pid) REFERENCES provinces(id));
SHOW INDEX from provinces\G;
SHOW INDEX from users\G;
Copy after login

2. 外键约束的参照操作

(1). CASCADE:从父表删除或更新且自动删除或更新子表中匹配的行

(2). SET NULL:从父表删除或更新行,并设置子表中的外键列为NULL。如果使用该选项,必须保证子表列没有指定NOT NULL

(3). RESTRICT:拒绝对父表的删除或更新操作。

(4). NO ACTION:标准SQL的关键字,在MySQL中与RESTRICT相同

例如:

CREATE TABLE users1(id SMALLINT UNSIGNED PRIMARY KEY AUTO_INCREMENT, username VARCHAR(10) NOT NULL, pid SMALLINT UNSIGNED, FOREIGN KEY(pid) REFERENCES provinces(id) ON DELETE CASCADE);
INSERT provinces(pname) VALUES('A');
INSERT provinces(pname) VALUES('B');
INSERT provinces(pname) VALUES('C');
INSERT users1(username, pid) VALUES('Tom', 3);
INSERT users1(username, pid) VALUES('Jerry', 1);
#查看我们添加的数据
SELECT * FROM users1;
#删除一个省份
DELETE FROM provinces WHERE id=3;
#查看省份
SELECT * FROM provinces;
#再查看人员表
SELECT * FROM users1;
Copy after login

3. 表级约束与列级约束

对一个数据列简历的约束,称为列级约束;对多个数据列建立的约束,称为表级约束。列级约束既可以在列定义时声明,也可以在列定义后声明。表级约束只能在列定以后声明。

4. 修改数据表

(1). 添加/删除列

添加单列:

ALTER TABLE tbl_name ADD [COLUMN] col_name column_definition [FIRST | AFTER col_name];

添加多列:

ALTER TABLE tbl_name ADD [COLUMN] (col_name column_definition,...);

删除列:

ALTER TABLE tbl_name DROP [COLUMN] col_name;

例如:

SHOW COLUMNS FROM users1;
ALTER TABLE users1 ADD age TINYINT UNSIGNED NOT NULL DEFAULT 10;
ALTER TABLE users1 ADD password VARCHAR(32) NOT NULL AFTER username;
ALTER TABLE users1 ADD truename VARCHAR(20) NOT NULL FIRST;
#然后查看一下users1结构
SHOW COLUMNS FROM users1;
ALTER TABLE users1 DROP truename;
ALTER TABLE users1 DROP password, DROP age;
#然后查看一下users1结构
SHOW COLUMNS FROM users1;
Copy after login
(2). 添加主键约束

ALTER TABLE tbl_name ADD [CONSTRAINT [symbol]] PRIMARY KEY [index_type] (index_col_name,...);

例如:

CREATE TABLE users2(username VARCHAR(10) NOT NULL, pid SMALLINT UNSIGNED);
SHOW CREATE TABLE users2;
ALTER TABLE users2 ADD id SMALLINT UNSIGNED;
SHOW COLUMNS FROM users2;
#设置id为主键
ALTER TABLE users2 ADD CONSTRAINT PK_users2_id PRIMARY KEY (id);
Copy after login
(3). 添加唯一约束:

ALTER TABLE tbl_name ADD [CONSTRAINT [symbol]] UNIQUE [INDEX | KEY] [index_name] [index_type] (index_col_name,...);

例如:

ALTER TABLE users2 ADD UNIQUE (username);
SHOW CREATE TABLE users2;
Copy after login
(4). 添加外键约束:

ALTER TABLE tbl_name ADD [CONSTRAINT [symbol]] FOREIGN KEY [index_name] (index_col_name,...) reference definition;

例如:

ALTER TABLE users2 ADD FOREIGN KEY (pid) REFERENCES provinces (id);
#查看
SHOW CREATE TABLE users2;
Copy after login
(5). 添加/删除默认约束:

ALTER TABLE tbl_name ALTER [COLUMN] col_name {SET DEFAULT literal | DROP DEFAULT};
例如:

ALTER TABLE users2 ADD age TINYINT UNSIGNED NOT NULL;
SHOW COLUMNS FROM users2;
#设置默认值
ALTER TABLE users2 ALTER age SET DEFAULT 15;
SHOW COLUMNS FROM users2;
#删除默认值
ALTER TABLE users2 ALTER age DROP DEFAULT;
SHOW COLUMNS FROM users2;
Copy after login
(6). 删除主键约束

ALTER TABLE tbl_name DROP PRIMARY KEY;

例如:

ALTER TABLE users2 DROP PRIMARY KEY;
# 查看
SHOW COLUMNS FROM users2;
Copy after login
(7). 删除唯一约束

ALTER TABLE tbl_name DROP {INDEX | KEY} index_name;

例如:

# 查看索引
SHOW INDEXES FROM users2\G;
ALTER TABLE users2 DROP INDEX username;
#查看
SHOW COLUMNS FROM users2;
# 再查看索引
SHOW INDEXES FROM users2\G;
Copy after login

(8). 删除外键约束

ALTER TABLE tbl_name DROP FOREIGN KEY fk_symbol;

例如:

SHOW CREATE TABLE users2;
ALTER TABLE users2 DROP FOREIGN KEY users2_ibfk_1;
# 查看外键不见了,但是pid索引还在
SHOW CREATE TABLE users2;
ALTER TABLE users2 DROP INDEX pid;
# pid索引也删除了
SHOW CREATE TABLE users2;
Copy after login
(9). 修改列定义

ALTER TABLE tbl_name MODIFY [COLUMN] col_name column_definition [FIRST | AFTER col_name];

例如:

SHOW CREATE TABLE users2;
# 将id放在最前面
ALTER TABLE users2 MODIFY id SMALLINT UNSIGNED FIRST;
SHOW COLUMNS FROM users2;
# 修改字段类型。 注意:由大类型修改为小类型有可能会造成数据的丢失。
ALTER TABLE users2 MODIFY id TINYINT UNSIGNED FIRST;
Copy after login
(10). 修改列名称

ALTER TABLE tbl_name CHANGE [COLUMN] old_col_name new_col_name column_definition [FIRST | AFTER col_name];

例如:

#修改列名称和类型
ALTER TABLE users2 CHANGE pid p_id TINYINT UNSIGNED NOT NULL;
SHOW COLUMNS FROM users2;
Copy after login
(11). 数据表更名

方法一:

ALTER TABLE tbl_name RENAME [TO | AS] new_tbl_name;

方法二:

RENAME TABLE tbl_name TO new_tbl_name [, tbl_name2 TO new_tbl_name2]...;

例如:

ALTER TABLE users2 RENAME users3;
SHOW TABLES;
RENAME TABLE users3 TO users2;
SHOW TABLES;
Copy after login

 


5. 总结

 

(1). 约束:

按功能划分:NOT NULL,PRIMARY KEY,UNIQUE KEY,DEFAULT, FOREIGN KEY

按数据列的数目划分:表级约束、列级约束

(2). 修改数据表:

针对字段的操作:添加/删除字段、修改列定义、修改列名称等

针对约束的操作:添加/删除各种约束

针对数据表的操作:数据表更名(两种方式)

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

Data table compression technology in MySQL Data table compression technology in MySQL Jun 16, 2023 am 08:16 AM

MySQL is a common relational database that is a core component of many websites and applications. As the amount of data becomes larger and larger, how to optimize the performance of MySQL becomes particularly important. One of the key areas is the compression of data tables. In this article we will introduce the data table compression technology in MySQL. Compressed tables and non-compressed tables There are two types of data tables in MySQL: compressed tables and non-compressed tables. Uncompressed tables are MySQL's default table type, which use fixed-length row format to store data. This means data

Data table DDL operation technology in MySQL Data table DDL operation technology in MySQL Jun 15, 2023 pm 07:55 PM

MySQL is a very popular open source relational database management system that supports complete DDL (data definition language) operations. DDL is a language used to define and manage various data objects in the database, including data tables, views, indexes, etc. It is very important for database administrators and developers to be proficient in DDL operation technology of data tables in MySQL. This article will introduce in detail the technology and methods of DDL operation of data tables in MySQL, and provide practical operation examples. 1. Create a data table. Creating a data table is in DDL.

mysql modify data table name mysql modify data table name Jun 20, 2023 pm 05:52 PM

MySQL modifies the data table: 1. First check all tables in the database, the code is: "SHOW TABLES;"; 2. Modify the table name, the code is: "ALTER TABLE old table name RENAME [TO] new table name;". 3. Check whether the table name is modified successfully. The code is: "SHOW TABLES;"

Data table reloading techniques in MySQL Data table reloading techniques in MySQL Jun 15, 2023 pm 11:28 PM

MySQL is an open source relational database management system. Its basic functions are excellent in database design, data storage and management. In MySQL, the data table is the most basic unit of data storage. In practical applications, data table reloading is a very common operating technique, which can help us improve the operating efficiency of the database and improve the stability of the system. This article will introduce this operation technique in detail from the concepts, principles and practical applications of data table overloading in MySQL. 1. What is data table overloading? Data table overloading is

How to calculate the average value of numeric columns in a data table using MySQL's AVG function How to calculate the average value of numeric columns in a data table using MySQL's AVG function Jul 24, 2023 pm 09:52 PM

Introduction to the method of using MySQL's AVG function to calculate the average value of numeric columns in a data table: MySQL is an open source relational database management system with a wealth of built-in functions to process and calculate data. Among them, the AVG function is a function used to calculate the average of a numeric column. This article will introduce how to use the AVG function to calculate the average value of numeric columns in a MySQL data table, and provide relevant code examples. 1. Create a sample data table First, we need to create a sample data table for demonstration. Suppose we have a file called

How to use thinkorm to implement related queries between data tables How to use thinkorm to implement related queries between data tables Aug 01, 2023 am 08:25 AM

How to use thinkorm to implement related queries between data tables Introduction: During database development, we often encounter situations where we need to perform related queries between multiple data tables. Using thinkorm, an excellent database ORM framework, you can easily implement associated queries of data tables and improve development efficiency. This article will introduce how to use thinkorm to implement related queries between data tables, and provide code examples to help readers better understand. 1. Basic concepts Before performing related queries, you first need to understand th

How to implement MySQL underlying optimization: horizontal and vertical splitting strategies for data tables How to implement MySQL underlying optimization: horizontal and vertical splitting strategies for data tables Nov 08, 2023 pm 06:57 PM

How to realize the underlying optimization of MySQL: horizontal and vertical partitioning strategies of data tables, which require specific code examples. Introduction: In large-scale application scenarios, MySQL databases often face the pressure of storing and querying massive data. In order to solve this problem, MySQL provides data table partitioning strategies, including horizontal partitioning (HorizontalPartitioning) and vertical partitioning (VerticalPartitioning). This article will introduce how to implement MySQL underlying optimization, focusing on

How to use the MAX function in MySQL to find the largest value in the data table How to use the MAX function in MySQL to find the largest value in the data table Jul 25, 2023 pm 09:49 PM

How to use the MAX function in MySQL to find the maximum value in the data table Introduction: In MySQL, we often need to perform various queries and analysis on the data table, including finding the maximum value in the data table. The maximum value in a data table can be easily found using the MAX function and is very useful when further processing the data. This article will introduce how to use the MAX function to find the largest value in the data table, and give corresponding code examples. 1. Introduction to the MAX function The MAX function is an aggregate function in MySQL. Use

See all articles