子查询(嵌套sql)
select语句是sql的查询。迄今为止我们所看到的所有select语句都是简单查询,即从单个数据库表中检索数据的单条语句。
sql还允许创建子查询,即嵌套在其他查询中的查询。
利用子查询进行过滤
若要跨表查询使用简单的sql语句需要如下
1.查询包含物品TNT2的所有订单编号
select order_num from orderitems where prod_id = 'TNT2';
2.查询对应订单编号的用户ID
select cust_id from orders where order_num in (20005,20007);
3.查询购买对应物品的用户信息
select cust_id,cust_name from customers where cust_id in (10001,10004);
至此经过三步查询获取到了客户的信息。
可以把其中的WHERE子句转换为子查询而不是硬编码这些SQL返回的数据:
转换为嵌套SQL,子查询
select cust_id,cust_name from customers where cust_id in(
select cust_id from orders where order_num in(
select order_num from orderitems where prod_id='TNT2')));
什么是嵌套查询,子查询
就是在一个sql当中,它的where条件来源于另外一个sql。
或者反过来理解,一个sql语句的结果,作为外层sql语句的条件。.
作为计算字段使用子查询
例:需要获取customers表中每个用户的订单总数
1.从customers表中获取用户列表
select cust_id,cust_name from customers;
2.获取一个用户在orders表中的订单数
select count(*) as orders_num from orders where cust_id = 10001;
3.考虑如何获取每个客户的订单数,对每个客户进行count函数的统计计算
–把count()作为一个子查询,即可作为计算字段进行子查询
select cust_id,cust_name,
(select count(*) from orders where orders.cust_id = customers.cust_id) as orders_num
from customers;