SQL必知必会 第11课 使用子查询
11.1 子查询
任何SQL语句都是查询,但此术语一般指SELECT语句。
SQL还允许创建子查询,即嵌套在其他查询中的查询。
11.2 利用子查询进行过滤
# 列出订购物品RGAN01的所有顾客
select cust_name, cust_contact
from customers
where cust_id IN (
select cust_id
from orders
where order_num IN(
select order_num
from orderitems
where prod_id = 'RGAN01'));
对于能嵌套的子查询的数目没有限制,不过由于性能的限制,不能嵌套太多的子查询。
11.3 作为计算字段使用子查询
# 列出customers表中每个顾客的订单总数
select cust_name, cust_state, (select count(*) from orders where orders.cust_id = customers.cust_id) as orders
from customers
order by cust_name;
其中orders是一个计算字段,它是由圆括号中的子查询建立的。
子查询中的where子句与前面使用的where子句稍有不同,因为它使用了完全限定列名,而不只是列名(cust_id)。
还没有评论,来说两句吧...