mysql 您所在的位置:网站首页 mysql键是什么 mysql

mysql

2024-06-18 15:34| 来源: 网络整理| 查看: 265

参考:

MySQL——约束(constraint)详解

constraint 约束概念

约束英文: constraint 英[kənˈstreɪnt] 美[kənˈstrent] n. 约束; 限制; 强制;

约束实际上就是表中数据的限制条件

约束种类

非空约束(not null):用not null约束的字段不能为null值,必须给定具体的数据 唯一性约束(unique): unique约束的字段,具有唯一性,不可重复,但可以为null 主键约束(primary key) PK 外键约束(foreign key) FK 检查约束(目前MySQL不支持、Oracle支持)

主键约束与“not null unique”区别

给某个字段添加主键约束之后,该字段不能重复也不能为空,效果和”not null unique”约束相同,但是本质不同。 主键约束除了可以做到”not null unique”之外,还会默认添加”索引——index”

外键约束(foreign key)FK

外键约束(foreign key)FK,只能是表级定义,外键其实就是引用.

foreign key(classno) references t_class(cno) 什么是外键

若有两个表A、B,

id是A的主键,而B中也有id字段,则id就是表B的外键,外键约束主要用来维护两个表之间数据的一致性。

A为基本表(比如:班级表),B为信息表(比如:学生表)

示例:

建表:

//表A带主键 create table t_class ( cno int(10) primary key, cname varchar(128) not null unique ); //表B带外键(关联A表进行约束) create table t_student ( sno int(10) primary key auto_increment, sname varchar(32) not null, classno int(3), foreign key (classno) references t_class (cno) );

插入数据:

insert into t_class (cno, cname) values (100, 'aaaaaaxxxxxx'); insert into t_class (cno, cname) values (200, 'oooooopppppp'); insert into t_student (sname, classno) values ('jack', 100); insert into t_student (sname, classno) values ('lucy', 100); insert into t_student (sname, classno) values ('king', 200);

查询:

select * from t_class;

在这里插入图片描述

select * from t_student;

在这里插入图片描述

select s.*, c.* from t_student s join t_class c on s.classno = c.cno;

在这里插入图片描述



【本文地址】

公司简介

联系我们

今日新闻

    推荐新闻

    专题文章
      CopyRight 2018-2019 实验室设备网 版权所有