SQL不仅支持单条的检索数据查询还允许创建子查询,即嵌套在其他查询中的查询。
表结构:/wsdfym/article/details/90722724
当前有用户表,以及订单表,订单详细表时,需要查询购买了某商品Id为“1001”的商品的客户信息
如果用单条语句查询需要
先从订单详细表查询商品ID为“1001”的购物订单ID再从订单表查询该购物订单id的用户id再根据用户id从用户表查询到用户信息
select order_numfrom orderitemswhere prod_id = 1001
2.
select cust_idfrom orderswhere order_num in (30007,30008)
3.
select cust_namefrom customerswhere cust_id in (1,2)
现在结合这三个查询,从外到内查询用户信息,查询该购物订单的顾客id,查询购买了该物品的订单id,
从内到外查询购买了该物品的订单id,查询该购物订单的顾客id,查询用户信息
select cust_namefrom customerswhere cust_id in ( select cust_idfrom orderswhere order_num in( select order_numfrom orderitemswhere prod_id = 1001))
该语句先执行最内层查询 “select order_num from orderitems where prod_id = 1001” 返回两个订单号 30007 ,30008,
依据内层查询返回的两个订单号 再执行中层查询 返回两个顾客id 1,2,最后依据返回的顾客id查询顾客信息