MySQL多表查询的方式

(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
  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值