MySQL 之 foreign key

前段回顾

create table 表名(    字段名1 类型[(宽度) 约束条件],    字段名2 类型[(宽度) 约束条件],    字段名3 类型[(宽度) 约束条件]    );

#解释:    类型:使用限制字段必须以什么样的数据类型传值    约束条件:约束条件是在类型之外添加一种额外的限制

# 注意:    1. 在同一张表中,字段名是不能相同    2. 宽度和约束条件可选,字段名和类型是必须的    3、最后一个字段后不加逗号

把所有数据都存放于一张表的弊端        1、表的组织结构复杂不清晰        2、浪费空间        3、扩展性极差

补充知识:    如果要清空表,使用truncate tb1;    作用:将整张表重置(包括id)

一、foreign key (重点)

表关系之多对一    1、寻找表与表之间的关系的套路

举例:emp表   dep表        步骤一:        part1:            1、先站在左表emp的角度            2、去找左表emp的多条记录能否对应右表dep的一条记录            3、翻译2的意义:                左表emp的多条记录==》多个员工                右表dep的一条记录==》一个部门

最终翻译结果:多个员工是否可以属于一个部门?                如果是则需要进行part2的流程

part2:            1、站在右表dep的角度            2、去找右表dep的多条记录能否对应左表emp的一条记录            3、翻译2的意义:                右表dep的多条记录==》多个部门                左表emp的一条记录==》一个员工

最终翻译结果:多个部门是否可以包含同一个员工

如果不可以,则可以确定emp与dep的关系只一个单向的多对一                如何实现?                    在emp表中新增一个dep_id字段,该字段指向dep表的id字段

# foreign key会带来什么样的效果?            #1、约束1:在创建表时,先建被关联的表dep,才能建关联表emp

create table dep(                id int primary key auto_increment,                dep_name char(10),                dep_comment char(60)            );

create table emp(                id int primary key auto_increment,                name char(16),                gender enum(‘male‘,‘female‘) not null default ‘male‘,                dep_id int,                foreign key(dep_id) references dep(id)            );

#2、约束2:在插入记录时,必须先插被关联的表dep,才能插关联表emp            insert into dep(dep_name,dep_comment) values            (‘sb教学部‘,‘sb辅导学生学习,教授python课程‘),            (‘外交部‘,‘老男孩上海校区驻张江形象大使‘),            (‘nb技术部‘,‘nb技术能力有限部门‘);

insert into emp(name,gender,dep_id)  values            (‘alex‘,‘male‘,1),            (‘egon‘,‘male‘,2),            (‘lxx‘,‘male‘,1),            (‘wxx‘,‘male‘,1),            (‘wenzhou‘,‘female‘,3);

#3、约束3:更新与删除都需要考虑到关联与被关联的关系            解决方案:            1、先删除关联表emp,再删除被关联表dep,准备重建            mysql> drop table emp;            Query OK, 0 rows affected (0.11 sec)

mysql> drop table dep;            Query OK, 0 rows affected (0.04 sec)

2、重建:新增功能,同步更新,同步删除            create table dep(                id int primary key auto_increment,                dep_name char(10),                dep_comment char(60)            );

create table emp(                id int primary key auto_increment,                name char(16),                gender enum(‘male‘,‘female‘) not null default ‘male‘,                dep_id int,                foreign key(dep_id) references dep(id)                on update cascade                on delete cascade            );            insert into dep(dep_name,dep_comment) values            (‘sb教学部‘,‘sb辅导学生学习,教授python课程‘),            (‘外交部‘,‘老男孩上海校区驻张江形象大使‘),            (‘nb技术部‘,‘nb技术能力有限部门‘);

insert into emp(name,gender,dep_id)  values            (‘alex‘,‘male‘,1),            (‘egon‘,‘male‘,2),            (‘lxx‘,‘male‘,1),            (‘wxx‘,‘male‘,1),            (‘wenzhou‘,‘female‘,3);

# 同步删除            mysql> select * from dep;            +----+------------------+------------------------------------------------------------------------------------------+            | id | dep_name         | dep_comment                                                                              |            +----+------------------+------------------------------------------------------------------------------------------+            |  1 | sb教学部         | sb辅导学生学习,教授python课程                                                           |            |  2 | 外交部           | 老男孩上海校区驻张江形象大使                                                             |            |  3 | nb技术部         | nb技术能力有限部门                                                                       |            +----+------------------+------------------------------------------------------------------------------------------+            3 rows in set (0.00 sec)

mysql> select * from emp;            +----+------------------+--------+--------+            | id | name             | gender | dep_id |            +----+------------------+--------+--------+            |  1 | alex             | male   |      1 |            |  2 | egon             | male   |      2 |            |  3 | lxx              | male   |      1 |            |  4 | wxx              | male   |      1 |            |  5 | wenzhou          | female |      3 |            +----+------------------+--------+--------+            5 rows in set (0.00 sec)

mysql> delete from dep where id=1;            Query OK, 1 row affected (0.02 sec)

mysql> select * from dep;            +----+------------------+------------------------------------------------------------------------------------------+            | id | dep_name         | dep_comment                                                                              |            +----+------------------+------------------------------------------------------------------------------------------+            |  2 | 外交部           | 老男孩上海校区驻张江形象大使                                                             |            |  3 | nb技术部         | nb技术能力有限部门                                                                       |            +----+------------------+------------------------------------------------------------------------------------------+            2 rows in set (0.00 sec)

mysql> select * from emp;            +----+------------------+--------+--------+            | id | name             | gender | dep_id |            +----+------------------+--------+--------+            |  2 | egon             | male   |      2 |            |  5 | wenzhou          | female |      3 |            +----+------------------+--------+--------+            2 rows in set (0.00 sec)

#同步更新            mysql> select * from emp;            +----+------------------+--------+--------+            | id | name             | gender | dep_id |            +----+------------------+--------+--------+            |  2 | egon             | male   |      2 |            |  5 | wenzhou          | female |      3 |            +----+------------------+--------+--------+            2 rows in set (0.00 sec)

mysql> update dep set id=200 where id =2;            Query OK, 1 row affected (0.04 sec)            Rows matched: 1  Changed: 1  Warnings: 0

mysql> select * from dep;            +-----+------------------+------------------------------------------------------------------------------------------+            | id  | dep_name         | dep_comment                                                                              |            +-----+------------------+------------------------------------------------------------------------------------------+            |   3 | nb技术部         | nb技术能力有限部门                                                                       |            | 200 | 外交部           | 老男孩上海校区驻张江形象大使                                                             |            +-----+------------------+------------------------------------------------------------------------------------------+            2 rows in set (0.00 sec)

mysql> select * from emp;            +----+------------------+--------+--------+            | id | name             | gender | dep_id |            +----+------------------+--------+--------+            |  2 | egon             | male   |    200 |            |  5 | wenzhou          | female |      3 |            +----+------------------+--------+--------+            2 rows in set (0.00 sec)

表关系之一对多

1、什么是多对多            两张表之间是一个双向的多对一关系,称之为多对多            如何实现?            建立第三张表,该表中有一个字段fk左表的id,还有一个字段是fk右表的id

create table author(                id int primary key auto_increment,                name char(16)            );

create table book(                id int primary key auto_increment,                bname char(16),                price int            );

insert into author(name) values            (‘egon‘),            (‘alex‘),            (‘wxx‘)            ;            insert into book(bname,price) values            (‘python从入门到入土‘,200),            (‘葵花宝典切割到精通‘,800),            (‘九阴真经‘,500),            (‘九阳神功‘,100)            ;

create table author2book(                id int primary key auto_increment,                author_id int,                book_id int,                foreign key(author_id) references author(id)                on update cascade                on delete cascade,                foreign key(book_id) references book(id)                on update cascade                on delete cascade            );

insert into author2book(author_id,book_id) values            (1,3),            (1,4),            (2,2),            (2,4),            (3,1),            (3,2),            (3,3),            (3,4);    表关系之一对一

左表的一条记录唯一对应右表的一条记录,反之也一样    本质就是在对应的存储id的字段加unique 来保证唯一存在        create table customer(            id int primary key auto_increment,            name char(20) not null,            qq char(10) not null,            phone char(16) not null        );

create table student(            id int primary key auto_increment,            class_name char(20) not null,            customer_id int unique, #该字段一定要是唯一的            foreign key(customer_id) references customer(id) #外键的字段一定要保证unique            on delete cascade            on update cascade        );

insert into customer(name,qq,phone) values        (‘李飞机‘,‘31811231‘,13811341220),        (‘王大炮‘,‘123123123‘,15213146809),        (‘守榴弹‘,‘283818181‘,1867141331),        (‘吴坦克‘,‘283818181‘,1851143312),        (‘赢火箭‘,‘888818181‘,1861243314),        (‘战地雷‘,‘112312312‘,18811431230)        ;

#增加学生        insert into student(class_name,customer_id) values        (‘脱产3班‘,3),        (‘周末19期‘,4),        (‘周末19期‘,5)        ;

二 插入数据INSERT

1. 插入完整数据(顺序插入)        语法一:        INSERT INTO 表名(字段1,字段2,字段3…字段n) VALUES(值1,值2,值3…值n);

语法二:        INSERT INTO 表名 VALUES (值1,值2,值3…值n);

2. 指定字段插入数据        语法:        INSERT INTO 表名(字段1,字段2,字段3…) VALUES (值1,值2,值3…);

3. 插入多条记录        语法:        INSERT INTO 表名 VALUES            (值1,值2,值3…值n),            (值1,值2,值3…值n),            (值1,值2,值3…值n);

4. 插入查询结果        语法:        INSERT INTO 表名(字段1,字段2,字段3…字段n)                        SELECT (字段1,字段2,字段3…字段n) FROM 表2                        WHERE …;

三 更新数据UPDATE

语法:        UPDATE 表名 SET            字段1=值1,            字段2=值2,            WHERE CONDITION;

示例:        UPDATE mysql.user SET password=password(‘123’)            where user=’root’ and host=’localhost’;

四 删除数据DELETE

语法:        DELETE FROM 表名            WHERE CONITION;

示例:        DELETE FROM mysql.user            WHERE password=’’;

练习:        更新MySQL root用户密码为mysql123        删除除从本地登录的root用户以外的所有用户

原文地址:https://www.cnblogs.com/zhaodafa/p/9017772.html

时间: 2024-08-30 05:18:39

MySQL 之 foreign key的相关文章

【MySQL】FOREIGN KEY

1 1 FOREIGN KEY reference PRIMARY KEY CREATE TABLE `roottb` ( `id` INT(11) UNSIGNED AUTO_INCREMENT NOT NULL, `data` VARCHAR(100) NOT NULL DEFAULT '', PRIMARY KEY (`id`) ) ENGINE =InnoDB; CREATE TABLE `subtb` ( `id` INT(11) UNSIGNED AUTO_INCREMENT NOT

MySQL Foreign Key

ntroduction to MySQL foreign key A foreign key is a field in a table that matches another field of another table. A foreign key places constraints on data in the related tables, which enables MySQL to maintain referential integrity. Let’s take a look

Mysql create constraint foreign key faild.trouble shooting method share

mysql> create table tb_test (id int(10) not null auto_increment primary key,action_id int(10) not null,error_code int(10) not null default 0,desc_key varchar(64) not null default 'audit.log.default',INDEX(action_id),constraint `FK_ACTIONID` foreign k

MYSQL外键(Foreign Key)的使用

转载自:http://www.cppblog.com/wolf/articles/69089.html#Post 原文实在太精辟又形象,忍不住转载过来留下笔记,像作者致敬 在MySQL 3.23.44版本后,InnoDB引擎类型的表支持了外键约束.外键的使用条件:1.两个表必须是InnoDB表,MyISAM表暂时不支持外键(据说以后的版本有可能支持,但至少目前不支持):2.外键列必须建立了索引,MySQL 4.1.2以后的版本在建立外键时会自动创建索引,但如果在较早的版本则需要显示建立: 3.外

MySQL foreign key - How to define a foreign key in MySQL

table of contents Creating a MySQL foreign key MySQL foreign key support in database engines MySQL foreign keys and ON UPDATE and ON DELETE MySQL foreign key FAQ: How do I define a foreign key in MySQL? Answer: Here's a quick example of how I typical

MYSQL: Cannot delete or update a parent row: a foreign key constraint fails

这可能是MySQL在InnoDB中设置了foreign key关联,造成无法更新或删除数据.可以通过设置FOREIGN_KEY_CHECKS变量来避免这种情况. SET FOREIGN_KEY_CHECKS = 0; 删除完成后设置 SET FOREIGN_KEY_CHECKS = 1; 其他: 关闭唯一性校验 set unique_checks=0; set unique_checks=1;

MySQL:ERROR 1217 (23000): Cannot delete or update a parent row: a foreign key constraint fails

MySQL在删除一张表时出现 ERROR 1217 (23000): Cannot delete or update a parent row: a foreign key constraint fails 可能是MySQL在InnoDB中设置了foreign key关联,造成无法更新或删除数据.可以通过设置FOREIGN_KEY_CHECKS变量来避免这种情况. SET FOREIGN_KEY_CHECKS = 0; 然后就可以删除表了. 删除完成后设置 SET FOREIGN_KEY_CHE

mysql foreign key(外键) 说明与实例

一,什么是foreign key,及其完整性 个人觉得,foreign key就是表与表之间的某种约定的关系,由于这种关系的存在,我们能够让表与表之间的数据,更加的完整,关连性更强.关于完整性,关连性我举个例子,大家就会明白了. 有二张表,一张是用户表,一张是订单表: 1,如果我删除了用户表里的用户,那么订单表里面根这个用户有关的数据,就成了无头数据了,不完整了. 2,如果我在订单表里面,随便插入了一条数据,这个订单在用户表里面,没有与之对应的用户.这样数据也不完整了. 如果有外键的话,就方便多

MySQL—FOREIGN KEY

作用:保持数据一致性,完整性.实现一对一或一对多关系.(学习的过程中,老师说,实际的生产中,一般不使用物理上的外键约束的,都是使用逻辑上的外键约束) 要求: 父表与子表的存储引擎必须相等,而且只能是InnoDB: 禁止使用临时表: 外键列和参照列的数据类型相同.数字的长度和是否有符号位必须相同.字符的长度则可以不同: 外键列和参照列必须创建索引.如果,外键列不存在索引的话,MySQL会自动创建索引. 约束的参照操作(在进行数据插入的时候,是先插入父表,在插入子表的) CASCADE:从父表删除或