(1)内连接
--隐示内连接
select 字段列表 from 表1 , 表2... where 条件;
-- 显示内连接
select 字段列表 from 表1,inner join 表2 on 条件;
内连接相当于查询A B的交集数据
隐士内连接和显示内连接没有任何的区别,查询出来的结构都是一样的,只不过这就是两种语法而已。
创建两张表(体现一对多的形式)
create table category(
cid int primary key auto_increment,
cname varchar(50) not null unique
);
create table product(
pid int primary key auto_increment,
pname varchar(50) not null ,
cid int ,
constraint FK_cid_cid foreign key (cid) references category(cid)
);
添加一些数据:
-- 笛卡尔积
select * from product,category;
select * from product,category where product.cid= category.cid;
select * from product,category inner join product p on category.cid = p.cid;
select p.* ,c.cid from category c inner join product p on c.cid = p.cid;
(2)外连接
左外连接和右外连接
-- 外连接
select p.pname,c.cname from product p inner join category c on p.cid = c.cid;
-- 左外连接
select p.pname,c.cname from product p left join category c on p.cid = c.cid;
-- 右外连接
select p.pname,c.cname from category c right join product p on p.cid = c.cid;
MySQL中不支持全连接。全连接不是笛卡尔积。
(3)子查询
子查询就是一个SQL语句查询的结果作为
子查询结果分为三种:
1)单行单列
使用比较运算符 >,<, >=, <=, = 等
2) 多行单列
使用in关键字
例如:
-- 创建一个产品表
create table product(
pid int primary key,
pname varchar(20),
price double,
category_id varchar(32)
);
-- 在表中添加一些数据
INSERT INTO product(pid,pname,price,category_id) VALUES(1,'联想',5000,'c001');
INSERT INTO product(pid,pname,price,category_id) VALUE