search
HomeDatabaseMysql TutorialMySQL学习笔记4:完整性约束限制字段

完整性约束是对字段进行限制,从而符合该字段达到我们期望的效果比如字段含有默认值,不能是NULL等如果插入的数据不满足限制要求,数据库管理系统就拒绝执行操作

完整性约束是对字段进行限制,从而符合该字段达到我们期望的效果比如字段含有默认值,不能是NULL等
直观点说:如果插入的数据不满足限制要求,数据库管理系统就拒绝执行操作
设置表的主键
主键能够标识表中每条信息的唯一性,如同身份证号码和人的关系
人可以同名,但是身份证号码却是唯一的,
创建主键的目的在于快速查找到表中的某一条信息
单字段主键
代码如下:
mysql> create table student(
-> id int primary key,
-> name varchar(20),
-> sex boolean
-> );
Query OK, 0 rows affected (0.09 sec)

创建了三个字段,其中id为主键
多字段主键
多字段主键由多个属性组合而成,在属性定义完之后统一设置主键
代码如下:
mysql> create table student2(
-> id int,
-> course_id int,
-> score float,
-> primary key(id,course_id)
-> );
Query OK, 0 rows affected (0.11 sec)

student2表有三个字段,其中id和course_id的组合可以确定唯一的一条记录
设置表的外键
表的外键与主键是相对应的,比如表A中的id是外键,表B中的id是主键
那么就可以称表B为父表,表A为子表
设置表外键的作用在于建立与父表的联系,比如表B中id为123的学生删除后,表A中id为123的记录也随着消失
这样做的目的在于保证表的完整性
代码如下:
mysql> create table student3(
-> id int primary key,
-> course_id int,
-> teacher varchar(20),
-> constraint fk foreign key(id,course_id)
-> references student2(id,course_id)
-> );
Query OK, 0 rows affected (0.12 sec)

这里创建student3表,constraint后面的fk是外键别名,foreign key也就是设置外键的字段
references后的内容表示父表,和父表中的主键
需要注意的是,父表中的主键不能为空,并且主键和外键的数据类型要一致
设置表的非空约束
非空性很好理解,就是设置表中字段的值不能为空(NULL)
如果在已经设置此约束性条件的字段中插入空值,数据库系统则会报错
代码如下:
mysql> create table student4(
-> id int not null,
-> name varchar(20),
-> sex boolean
-> );
Query OK, 0 rows affected (0.10 sec)

这里的not null就是约束条件
设置表的唯一性约束
唯一性是指表中该字段的值不能重复出现,设置表的唯一性约束
也就是给表中某个字段加上unique
代码如下:
mysql> create table student5(
-> id int unique,
-> name varchar(20)
-> );
Query OK, 0 rows affected (0.10 sec)

此处id字段便不可重复
设置表的属性值自动增加
auto_increment主要用于为表中插入的新记录自动生成唯一的ID
一个表只能有一个字段使用auto_increment约束
并且该字段必须为主键的一部分
代码如下:
mysql> create table student6(
-> id int primary key auto_increment,
-> name varchar(20)
-> );
Query OK, 0 rows affected (0.12 sec)

这里的id是主键,并且会自动增加id值,比如1,2,3,4……
需要注意的是,auto_increment约束的值必须是整数类型
设置表中属性的默认值
在表中插入一条新的记录时,如果没有为该字段赋值
那么数据库系统会自动为该字段赋上一条默认值
代码如下:
mysql> create table student7(
-> id int primary key,
-> score int default 0
-> );
Query OK, 0 rows affected (0.10 sec)
Statement
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
MySQL: BLOB and other no-sql storage, what are the differences?MySQL: BLOB and other no-sql storage, what are the differences?May 13, 2025 am 12:14 AM

MySQL'sBLOBissuitableforstoringbinarydatawithinarelationaldatabase,whileNoSQLoptionslikeMongoDB,Redis,andCassandraofferflexible,scalablesolutionsforunstructureddata.BLOBissimplerbutcanslowdownperformancewithlargedata;NoSQLprovidesbetterscalabilityand

MySQL Add User: Syntax, Options, and Security Best PracticesMySQL Add User: Syntax, Options, and Security Best PracticesMay 13, 2025 am 12:12 AM

ToaddauserinMySQL,use:CREATEUSER'username'@'host'IDENTIFIEDBY'password';Here'showtodoitsecurely:1)Choosethehostcarefullytocontrolaccess.2)SetresourcelimitswithoptionslikeMAX_QUERIES_PER_HOUR.3)Usestrong,uniquepasswords.4)EnforceSSL/TLSconnectionswith

MySQL: How to avoid String Data Types common mistakes?MySQL: How to avoid String Data Types common mistakes?May 13, 2025 am 12:09 AM

ToavoidcommonmistakeswithstringdatatypesinMySQL,understandstringtypenuances,choosetherighttype,andmanageencodingandcollationsettingseffectively.1)UseCHARforfixed-lengthstrings,VARCHARforvariable-length,andTEXT/BLOBforlargerdata.2)Setcorrectcharacters

MySQL: String Data Types and ENUMs?MySQL: String Data Types and ENUMs?May 13, 2025 am 12:05 AM

MySQloffersechar, Varchar, text, Anddenumforstringdata.usecharforfixed-Lengthstrings, VarcharerForvariable-Length, text forlarger text, AndenumforenforcingdataAntegritywithaetofvalues.

MySQL BLOB: how to optimize BLOBs requestsMySQL BLOB: how to optimize BLOBs requestsMay 13, 2025 am 12:03 AM

Optimizing MySQLBLOB requests can be done through the following strategies: 1. Reduce the frequency of BLOB query, use independent requests or delay loading; 2. Select the appropriate BLOB type (such as TINYBLOB); 3. Separate the BLOB data into separate tables; 4. Compress the BLOB data at the application layer; 5. Index the BLOB metadata. These methods can effectively improve performance by combining monitoring, caching and data sharding in actual applications.

Adding Users to MySQL: The Complete TutorialAdding Users to MySQL: The Complete TutorialMay 12, 2025 am 12:14 AM

Mastering the method of adding MySQL users is crucial for database administrators and developers because it ensures the security and access control of the database. 1) Create a new user using the CREATEUSER command, 2) Assign permissions through the GRANT command, 3) Use FLUSHPRIVILEGES to ensure permissions take effect, 4) Regularly audit and clean user accounts to maintain performance and security.

Mastering MySQL String Data Types: VARCHAR vs. TEXT vs. CHARMastering MySQL String Data Types: VARCHAR vs. TEXT vs. CHARMay 12, 2025 am 12:12 AM

ChooseCHARforfixed-lengthdata,VARCHARforvariable-lengthdata,andTEXTforlargetextfields.1)CHARisefficientforconsistent-lengthdatalikecodes.2)VARCHARsuitsvariable-lengthdatalikenames,balancingflexibilityandperformance.3)TEXTisidealforlargetextslikeartic

MySQL: String Data Types and Indexing: Best PracticesMySQL: String Data Types and Indexing: Best PracticesMay 12, 2025 am 12:11 AM

Best practices for handling string data types and indexes in MySQL include: 1) Selecting the appropriate string type, such as CHAR for fixed length, VARCHAR for variable length, and TEXT for large text; 2) Be cautious in indexing, avoid over-indexing, and create indexes for common queries; 3) Use prefix indexes and full-text indexes to optimize long string searches; 4) Regularly monitor and optimize indexes to keep indexes small and efficient. Through these methods, we can balance read and write performance and improve database efficiency.

See all articles

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

Hot Tools

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor