前期准备:
use day;
创建商品种类表
create table category(
cid varchar(32) primary key,
cname varchar(100)
);
创建商品表
create table product(
pid varchar(32) primary key,
pname varchar(40),
price double,
category_id varchar(32)
);
insert into category(cid,cname) values('c001','家电');
insert into category(cid,cname) values('c002','服饰'); insert into category(cid,cname) values('c003','化妆品');
insert into product(pid,pname,price,category_id) values('p001','联想','5000','c001');
insert into product(pid,pname,price,category_id) values('p002','海尔','5000','c001');
insert into product(pid,pname,price,category_id) values('p003','雷神','5000','c001');
insert into product(pid,pname,price,category_id) values('p004','JACK JONES','800','c002');
insert into product(pid,pname,price,category_id) values('p005','真维斯','200','c002');
insert into product(pid,pname,price,category_id) values('p006','花花公子','440','c002');
insert into product(pid,pname,price,category_id) values('p007','劲霸','2000','c002');
insert into product(pid,pname,price,category_id) values('p008','香奈儿','800','c003');
insert into product(pid,pname,price,category_id) values('p009','相宜本草','200','c003');
category表:
product表:
外键约束的声明:
-- 4.添加约束 (constraint product_fk可以不写)
-- alter table product add constraint product_fk foreign key(category_id) references category(cid);
内连接:
隐式内连接
SELECT distinct cname from category c,product p where c.cid=p.category_id;
显内连接式
SELECT distinct cname from category c inner join product p where c.cid=p.category_id;
查询结果:
左外连接:
SELECT * from category c left join product p on c.cid=p.category_id;
右外连接:
SELECT * from category c right join product p on c.cid=p.category_id;
运行结果:
子查询定义:
SELECT * from product where category_id=(SELECT cid from category where cname='化妆品');
运行结果: