七、子查询

7.1 子查询过滤
嵌套在其他查询中的查询,where子句中是一个select查询语句。 嵌套层数没有限制。
order表存储订单号、客户ID、订单日期;orderitem表存储物品信息(价格,数量,总金额,产品名称,产等)
>>> select order_id from orderitems where prod_name='TNT2';
>>> select cust_id from orders where order_id in (20005;20006); #2) 20005,20006是1)的查询结果。
合并:
>>> select cust_id from orders where order_id in (select order_id from orderitems where prod_name='TNT2');

【注】 列必须匹配,通常子查询将返回单个列并且与单个列匹配。

7.2 子查询作为计算字段
查询每个客户的订单总数:
>>> select count(*) as num from orders where cust_id = 10001;
>>> select cust_name,cust_state,(select count(*) from orders where order.cust_id=customers.cust_id) as num from customers order by cust_name;
【注】完全限定列名:order.cust_id=customers.cust_id



posted @ 2023-04-12 17:55  5250  阅读(30)  评论(0)    收藏  举报