数据准备
查询家电分类下,都有哪些商品,需要有分类表+商品表
#创建db3_2数据库,指定编码
create database db3_2 character set utf8;
#创建分类表与商品表
#分类表(一方 主表)
create table category(
cid varchar(32) primary key,
cname varchar(50)
);
#商品表(多方 从表)
create table products(
pid varchar(32) primary key,
pname varchar(50),
price int,
flag varchar(2),#是否上架标记为:1表示上架、0表示下架
category_id varchar(32),
--添加外键约束
foreign key(category_id) references category(cid)
);
#分类数据
insert into category(cid,cname) values('c001','家电');
insert into category(cid,cname) values('c002','鞋服');
insert into category(cid,cname) values('c003','化妆品');
insert into category(cid,cname) values('c004','汽车');
#商品数据
insert into products(pid,pname,price,flag,category_id) values('p001','小米电视机',5000,'1','c001');
insert into products(pid,pname,price,flag,category_id) values('p002','格力空诚',3000,'1','c001');
insert into products(pid,pname,price,flag,category_id) values('p003','美的冰箱',4500,'1','c001');
insert into products(pid,pname,price,flag,category_id) values('p004','篮球鞋',800,'1','c002');
insert into products (pid,pname,price,flag,category_id) values('p005','运动裤',200,'1','c002');
insert into products (pid,pname,price,flag,category_id) values('p006','T恤',300,'1','c002');
insert into products (pid,pname,price,flag,category_id) values('p007','冲锋衣',2000,'1','c002');
insert into products (pid,pname,price,flag,category_id) values('p008 ','神仙水',800, '1','c003');
insert into products (pid,pname,price,flag,category_id) values('p009','大宝',200,'1','c003');
多表关联内联接
笛卡尔积+where条件,实现查询家电分类下的所有商品
笛卡尔积
#笛卡尔积
select * from category c ,products p where cname = '家电'
笛卡尔积+where
#笛卡尔积+where
select * from category c ,products p where c.cid = p.category_id and cname = '家电';
显式内连接
查询所有商品信息和对应的分类信息
select * from category c inner join products p on c.cid = p.category_id
子查询
通过子查询的方式,查询价格最高的商品信息
#查询最高的价格
select max(price) from products;
#查询价格最高的商品信息
select * from products where price = (select max(price) from products);
查询价格小于2000的商品,来自于哪些分类(分类名称)
#查询价格小于2000的商品信息
select distinct(category_id) from products where price<2000;
#查询价格小于2000的商品,来自于哪些分类
select *
from products
where cid in (select distinct(category_id)
from products
where price<2000);