首页 > 代码库 > Mysql多表查询

Mysql多表查询

多表的查询建立在存在外键的基础上的几张表

首先创建4张表product、order、orderitem、category,分别代表:商品表、订单表、订单项表、商品类别表

代码如下:

-- 商品表
create table product(
    pid varchar(32) primary key,
    pname varchar(100),
    price double,
    category_id varchar(32)
);
-- 订单表
create table orders(
    oid varchar(32) primary key,
    totalprice double
);

-- 订单项表
create table orderitem(
    oid varchar(50),
    pid varchar(50)
);

-- 分类表
create table category(
    cid varchar(32) primary key,
    cname varchar(100)
);

 

分析:商品与订单之间是多对一关系,商品与类别之间是多对对一关系,订单与商品是多对多关系,我们可以通过订单项表来实现

建立主外键关系的代码如下:

alter table product add foreign key(category_id) references category(cid);

-- 2个主键确定一个  联合主键
alter table orderitem add primary key(oid,pid);
-- 订单表和订单项之间的主外键关系
alter table orderitem add foreign key(oid) references orders(oid);
-- 商品表和订单项表的主外键关系
alter table orderitem add foreign key(pid) references product(pid);

查询1、交叉连接查询(得到笛卡尔积,会很乱,也不是我们想要的结果)

select * from product,category;

查询2、内连接查询 (分为显式内连接查询和隐式内连接查询)

-- 内连接  inner jion  inner可以省略  内连接查询的是交集的部分
    -- 显示内连接查询后面有on主表的主键与从表的外键关系
select * from category inner join product on cid=category_id
-- 隐式内连接    查询结果一样的  常用
select * from category c,product p where c.cid=p.category_id;

得到的结果是当category表与product表的交集部分

查询3、外连接查询(分为左外连接和右外连接查询)

-- 外连接查询分为左外连接与右外连接
    -- 左外连接
select * from category left join product on cid=category_id;

    -- 右外连接
select * from category right join product on cid=category_id;

左外连接和右外连接的区别如下图

技术分享

 

  子查询:使用一个sql查询的结果作为另外一个sql查询的条件,如下所示

select * from product where category_id=(select cid from category where cname=化妆品);

 

Mysql多表查询