自学内容网 自学内容网

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;

在这里插入图片描述


原文地址:https://blog.csdn.net/qq_51504246/article/details/142962881

免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!