什么是mysql子查询_MySQL子查询

子查询:

就是一个查询的结果,可以作为另一个查询的数据源或者条件

注意:

组函数不能嵌套

例如:

如何查询book表中最贵的书的书名:

此处可查询条件: 书名 价格 最大价格

法一:

将查询结果作为另一个查询的条件:

例:

select name,price from book where price = (select max(price) from book);

法二:

等值比较 关键字 in

select name,price from book where price in(select max(price) from book where price);

例:

此处提供一张book表,表中有如下 数据:

num

name

price

sell

type

1120

test-1

10

yes

S

1150

test-2

13

no

S

1122

test-3

20

no

T

1125

test-4

23

yes

T

在外面查询中,查询的结果作为另一个查询的数据源时,需要将其当成一张表,在当成表的过程中,必须起别名;

例:

select max(avg_price) from (select avg(price) avg_price,type from book group by type) avg_table;

此处结尾处 的 avg_table 就是一个别名,根据需求自定义

平均price最大的type:(此处比较绕,请耐心分析)

select avg_price,type from (select avg(price) avg_price,type from book group by type) e where avg_price = (select max(avg_price) from (select avg(price) avg_price,type from book group by type) avg_table);

此处的 e 是一个表的别名

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值