mysql的多表操作

一对多的操做

开发过程中表示一对多关系,一般称一方为为主表或一表,多方为从表或者多表,为了表示一对多的关系,一般会在多表的一方添加一个字段(主表名称_id)字段类型一般和主表的主键类型一致,并称这个字段为外键;
例如订单和用户的一对多关系中我们使用如下代码表示

--创建用户表
create table user(
id int primary key auto_increment,
username varchar(20)
);
--创建订单表
create table orders(
id int primary key auto_increment,
price double,
user_id int
);

为了保证数据的完整性和有效性,添加约束(外键约束)
在多表一方添加外键约束
格式 alter table 多表名称 add foreign key(外键名称) references 表名称(主键)
例如

alter table orders add foreign key(user_id) references user(id);

添加了外键约束有如下特点:

  • 主表中不能删除从表中已引用的数据

  • 从表中不能添加主表没有的数据

多对多的操做

开发过程中表示多对多关系,一般引入一张中间表,在中间表中存放两张表的主键,一般还会将这两个主键设为中间表的联合主键
例如订单和商品的多对多关系中我们使用如下代码表示

--创建订单表
create table orders(
id int primary key auto_increment,
price double,
user_id int
);
--创建商品表
create table product(
id int primary key auto_increment,
name varchar(20),
price double
);
--创建中间表
create table oder_product(
product_id int,
orders_id int
);

为了保证数据的完整性和有效性,添加约束(外键约束)
多对多的关系在引入中间表后就可以看成是两个一对多,所以在中间表中添加两个外键约束,外键约束如下

--添加外键约束
alter table oder_product add foreign key(product_id) references product(id);
alter table oder_product add foreign key(orders_id) references orders(id);

多表查询

笛卡儿积

多张表无条件的联合查询,没有任何意义

select a.*,b.* from a,b;

内连接

语法格式一:显试的内连接

select a.*,b.* from a [inner] join b on ab的连接条件

语法格式二:隐试的内连接

select a.*,b.* from a,b where ab的连接条件

外连接

左外连接:

select a.*,b.* from a left [outer] join b on 连接条件

含义

先展示join左边表(a)的数据,根据条件再查询join右边表(b)的数据,满足条件则展示,不满足条件以null展示。

右外连接

select a.*,b.* from a right [outer] join b on 连接条件
含义:
先展示join右边表(b)的数据,根据条件再查询join左边表(a)的数据,满足条件则展示,不满足条件以null展示。

猜你喜欢

转载自blog.csdn.net/qq_36594966/article/details/81052166