欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 科技 > 名人名企 > MySQL-多表查询

MySQL-多表查询

2024/10/23 23:29:36 来源:https://blog.csdn.net/qq_51504246/article/details/142962881  浏览:    关键词:MySQL-多表查询

子查询[分步走]

在这里插入图片描述

1:一个sql的查询结果当做另一个sql的查询条件.
2:内层的那个sql语句要先执行

在这里插入图片描述

```sql
-- todo --------------子查询---(嵌套查询)---------------
-- 例如,使用命令完成:
-- (1)使用数据库班级db_product3下的商品表和分类表来操作;
-- (2)查询商品表、分类表的所有数据信息;
select * from tb_product;
select * from tb_category;
-- (3)查询分类为"服装"的所有商品信息;[分类id、商品]
select cid from tb_category where cname = '服装';
select * from tb_product where cid = (select cid from tb_category where cname = '服装');-- (4)查询商品名称为"格力"的分类信息;
select cid from tb_product where name = '格力';
select cname from tb_category where cid = (select cid from tb_product where name = '格力');-- (5) 查询商品价格高于平均价格的商品信息
select * from tb_product where price > (select avg(price) from tb_product);

交叉连接[了解]

在这里插入图片描述

-- todo 交叉连接---笛卡尔积查询----[了解]---------
# 语法1:
select * from table_category,table_product;
# 语法2:
select * from table_product cross join table_category;

内连接

在这里插入图片描述

查询的是两个表的交集.

在这里插入图片描述

-- todo 内连接查询 --[掌握]--------------
# 例如,使用内连接查询命令完成:
# (1)使用隐式内连接查询类别表和商品表的共有数据信息;
# select * from table_category,table_product where table_category.cid = table_product.category_id;
select * from table_product tp,table_category tc where tc.cid = tp.category_id;-- 使用别名
# (2)使用显式内连接来查询类别表和商品表的公共商品信息;
select * from table_category tc inner join table_product tp on tc.cid = tp.category_id;
select * from table_category tc  join table_product tp on tc.cid = tp.category_id; -- 省略inner

在这里插入图片描述

左外连接

在这里插入图片描述
在这里插入图片描述

左连接查询的是:左表的全部和右边表能连接上的数据.
左边特有的数据:右边没有的值用null填充
# -- todo 左外连接查询-----------左边的全部和右表中能关联的数据.
# 例如,使用左外连接查询命令完成:
# (1)以左表为主,连接查询类别表和商品表中的所有商品数据信息
select * from table_category tc left join table_product tp on tc.cid = tp.category_id;
#(2)以左表为主,连接查询商品表和类别表中的所有商品数据信息
select * from table_product tp left join table_category tc  on tc.cid = tp.category_id;

在这里插入图片描述

右连接[了解]

在这里插入图片描述

右连接查询的是:右表的全部和左边表能连接上的数据.
右边特有的数据:左边没有的值用null填充

在这里插入图片描述

# -- todo 右外连接查询-----------右边的全部和左表中能关联的数据.[了解]
select * from table_category tc right join table_product tp on tc.cid = tp.category_id;

在这里插入图片描述

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com