【MySQL】如何使用“子查询”

目录

什么是子查询?

使用场景1

使用场景2

注意


什么是子查询?

子查询简单来说就是嵌套在其他查询里面的查询。


使用场景1

1、比如现在有一堆订单数据,其中订单号(order_num)和对应的买家id(cust_id),订单日期(order_data)等放在orders表里面:

orders
order_numcust_idorder_data

但是具体的订单项包括买了什么物品(prod_id),每个物品的数量(prod_num)以及对应的订单号(order_num)放在orderitems表里面 :

orderitesms
prod_idprod_numorder_num

 而关于客户id(cust_id),客户姓名(cust_name),客户地址(cust_location)等具体信息又在cuntomers表里面:

customers
cust_idcust_namecust_location

现在要统计购买物品为:“内裤”的所有用户,此时就可以使用子查询。

首先如果不使用子查询,那么需要按照下面这样一步一步来执行:

1、查询orderirems里面包含“内裤”的所有订单号:

select order_num 
from orderitems 
where prod_id='内裤';

2、然后根据上面的order_num在customers表里面查询该订单号对应的用户,比如查询到了订单号为2001,2002:

select cust_id 
from customers 
where order_num in (2001,2002);

可以发现这样非常麻烦。

而如果如果使用子查询:

select cust_id 
from orders 
where order_num in (select order_num from orderitems where prod_id='内裤');

则十分简洁。


使用场景2

子查询的另外一个作用是作为计算字段(统计总数)。

比如统计cuntomers表里面每个客户下的订单总数是多少。

一般的流程是现在cumtomers表里面检索出所有用户,然后在orders表里面根据之前检索出的用户id来统计。如果使用子查询的话,如下:

select cust_name, cust_location,
           (select count(*) from orders 
            where orders.cust_id=customers.cust_id ) as totalorders)
from customers  
order by  cust_name;

最后得到的结果为:

结果
cust_namecust_locationtotalorders
Mr.handsomNanjing3
,,,(省略),,,,,,

注意

但是注意,子查询的效率不高,还是推荐使用联结join来查询,另外使用时可以比较一下两种写法需要的时间。

如果想了解联结(join)的具体用法,我一看看我的另一篇博客:点这里

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值