好好准备,期待新的工作来临。
2020-06-16
使用子查询
作为计算字段使用子查询
#查找每个顾客的总订单数
#orders中的cust_id与customer中cust_id相等
select cust_name,cust_state,
(select count(*) from orders where orders.cust_id=customers.cust_id) as orders
from customers order by cust_name;
使用子查询进行过滤
#猜想第一步
select cust_id from orders where order_num in(
select order_num from orderitems where prod_id='TNT2');
#返回结果 10001,10004
#猜想第二步
mysql> select cust_name,cust_contact from customers where cust_id in(10001,10004);
+----------------+--------------+
| cust_name | cust_contact |
+----------------+--------------+
| Coyote Inc. | Y Lee |
| Yosemite Place | Y Sam |
+----------------+--------------+
#与上面的结果一致
select cust_name,cust_contact from customers where cust_id in(select cust_id from orders where order_num in(
select order_num from orderitems where prod_id='TNT2'));
+----------------+--------------+
| cust_name | cust_contact |
+----------------+--------------+
| Coyote Inc. | Y Lee |
| Yosemite Place | Y Sam |
+----------------+--------------+
本文深入探讨了SQL子查询的应用,包括作为计算字段使用子查询来查找每个顾客的总订单数,以及如何使用子查询进行过滤,通过两步猜想实现特定产品的购买者筛选。通过实际案例,读者可以了解到子查询在复杂查询中的作用。
596

被折叠的 条评论
为什么被折叠?



