即嵌套在其他查询中的查询
select order_num from OrderItems where prod_id = ‘RGAN01‘;
可以得到,select cust_id from Orders where order_num in (20007,20008);
可以得到,select cust_name,cust_contact from Customers where cust_id in (‘1000000004‘,‘1000000005‘);
可以得到,总结:
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‘));
需要注意的地方:1. 作为子查询的SELECT
语句只能查询单个列,企图检索多个列将返回错误;2. 对于能嵌套的子查询的数目没有限制,不过在实际使用的时候由于性能的限制,不能嵌套太多的子查询。
select cust_name,cust_state,cust_id from Customers order by cust_name;
select count(*) from Orders where cust_id = ‘1000000003‘;
select cust_name, cust_state , (select count(*) from Orders where Orders.cust_id = Customers.cust_id) from Customers order by cust_name;
其中,where Orders.cust_id = Customers.cust_id
表示比较从Orders表中的cust_id和当前正从Customers表中检索出的cust_id。
另外,虽然样例可以完成需求,但并不是解决这种数据检索的最有效方法,后面讲到JOIN
方法时我们会重新做这道题。
原文:https://www.cnblogs.com/xLI4n/p/10346323.html