目录
什么是子查询?
子查询简单来说就是嵌套在其他查询里面的查询。
使用场景1
1、比如现在有一堆订单数据,其中订单号(order_num)和对应的买家id(cust_id),订单日期(order_data)等放在orders表里面:
order_num | cust_id | order_data |
但是具体的订单项包括买了什么物品(prod_id),每个物品的数量(prod_num)以及对应的订单号(order_num)放在orderitems表里面 :
prod_id | prod_num | order_num |
而关于客户id(cust_id),客户姓名(cust_name),客户地址(cust_location)等具体信息又在cuntomers表里面:
cust_id | cust_name | cust_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_name | cust_location | totalorders |
Mr.handsom | Nanjing | 3 |
,,,(省略) | ,,, | ,,, |
注意
但是注意,子查询的效率不高,还是推荐使用联结join来查询,另外使用时可以比较一下两种写法需要的时间。
如果想了解联结(join)的具体用法,我一看看我的另一篇博客:点这里。