1 利用子查询进行过滤

列出订购物品TNT2的所有客户

  1. 检索包含物品TNT2的所有订单的编号;
  2. 检索具有前一步骤列出的订单编号的所有客户的ID;
  3. 检索前一步骤返回的所有客户ID的客户信息;

select order_num
from orderitems
where prod_id='TNT2';

MySQL必知必会学习笔记(5)—— 子查询

select cust_id
from orders
where order_num IN (20005,20007);

MySQL必知必会学习笔记(5)—— 子查询

select cust_id
from orders
where order_num IN (
SELECT order_num from orderitems
WHERE prod_id='TNT2');

MySQL必知必会学习笔记(5)—— 子查询


SELECT cust_name,cust_contact
from customers
where cust_id IN (10001,10004);

MySQL必知必会学习笔记(5)—— 子查询

2 作为计算字段使用子查询

问题:需要显示 customers 表中每个客户的订单总数。(订单与相应的客户ID存储在orders表中)

  1. 从 customers 表中检索客户列表;
  2. 对于检索出的每个客户,统计其在orders 表中的订单数目;

MySQL必知必会学习笔记(5)—— 子查询
MySQL必知必会学习笔记(5)—— 子查询


SELECT cust_name,cust_state,
(SELECT COUNT(*) from orders WHERE
orders.cust_id=customers.cust_id) as orders
from customers
order by cust_name;

MySQL必知必会学习笔记(5)—— 子查询

相关文章:

  • 2021-07-01
  • 2022-02-08
  • 2021-12-22
  • 2021-11-23
  • 2021-08-04
  • 2021-08-13
  • 2022-12-23
猜你喜欢
  • 2021-04-06
  • 2021-05-26
  • 2021-12-07
  • 2021-05-24
  • 2021-08-19
  • 2022-12-23
  • 2022-12-23
相关资源
相似解决方案