sql语句 多表查询

多表的查询介绍

  • 初始化数据
  • 实际项目中,数据保存于多个表,如果需要的数据来自多个表,就要使用多表查询
  • 查询的分类
    》1:交叉连接查询(了解)
    》2:内连接查询
    隐式内连接,显式内连接***
    》3:外连接查询
    左外连接, 右外连接
    》4:子查询

交叉连接查询

  • 什么叫做交叉连接查询
    交叉连接查询是将两张表相乘: A和B —> A * B
  • 笛卡尔集
    两张表相乘的结果,不论数据是否正确
    在这里插入图片描述
  • 多表查询的本质
    多表查询可以理解成在笛卡尔集的基础上进行条件筛选

内连接

  • 什么是内连接查询
    求的是多张表的交集
    本质就是在笛卡尔集上加条件
  • 分类
    隐式内连接:select * from A,B where 条件;
    显式内连接:select * from A inner join B on 条件;(效率更高)
  • 区别
    使用关键字 inner join
    前者在笛卡尔集的基础上筛选,后者在原始表上筛选
  • 练习
隐式内连接:select * from A,B where 条件;

select * from category c,products p where c.cid = p.category_id;

显式内连接:select * from A inner join B on 条件;(效率更高)

select * from category c inner	join products p on c.cid = p.category_id;
select * from province,city;
select * from province p inner join city c on p.pid = c.pid_fk;

外连接查询

  • 什么是外连接查询
    两个表中选一个表将数据全部输出,另一个表没有对应数据则输出NULL
  • 分类
    左外连接
    select * from A left outer join B on 条件;
    以左表为主,左表中的数据全部输出,右表中如果没有同等的数据则补NULL
    右外连接
    select * from A right outer join B on 条件;
    以右表为主,右表中的数据全部输出,左表中如果没有同等的数据则补NULL
    在这里插入图片描述
# 外连接
select * from province p inner join city c on p.pid = c.pid_fk;
# 左外连接
select * from province p left outer join city c on p.pid = c.pid_fk;
# 右外连接
select * from province p right outer join city c on p.pid = c.pid_fk;

子查询

  • 什么叫子查询
    select的嵌套,一个select的查询结果作为另一个select查询语法的一部分
  • 案例
    在商品表中查询属于电子分类的商品
select *from product where cid = 1
select cid from category where cname='电子'

select *from product where cid = (select cid from category where cname='电子')

猜你喜欢

转载自blog.csdn.net/xinxin_____/article/details/108761801