SQL不仅支持单条的检索数据查询还允许创建子查询,即嵌套在其他查询中的查询。
表结构:https://blog.csdn.net/wsdfym/article/details/90722724
当前有用户表,以及订单表,订单详细表时,需要查询购买了某商品Id为“1001”的商品的客户信息

如果用单条语句查询需要

  • 先从订单详细表查询商品ID为“1001”的购物订单ID
  • 再从订单表查询该购物订单id的用户id
  • 再根据用户id从用户表查询到用户信息
select order_num
from orderitems
where prod_id = 1001

MySQL多表查询where子查询
2.

select cust_id
from orders
where order_num in (30007,30008)

MySQL多表查询where子查询
3.

select cust_name
from customers
where cust_id in (1,2)

MySQL多表查询where子查询
现在结合这三个查询,从外到内 查询用户信息,查询该购物订单的顾客id,查询购买了该物品的订单id,
从内到外查询购买了该物品的订单id,查询该购物订单的顾客id,查询用户信息

select 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 = 1001
																		)
								)

MySQL多表查询where子查询
该语句先执行最内层查询 “select order_num from orderitems where prod_id = 1001” 返回两个订单号 30007 ,30008,
依据内层查询返回的两个订单号 再执行中层查询 返回两个顾客id 1,2,最后依据返回的顾客id查询顾客信息

需要注意的是作为子查询只能返回单列,并且使用子查询并总是检索数据最有效的方法

相关文章: