查询(query)任何SQL语句都是查询。但此术语一般指SELECT语句。
SQL还允许创建子查询(subquery),即:嵌套在其他查询中的查询。
SELECT cust_id
FROM Orders
WHERE order_num IN(SELECT order_num
FROM OrderItems
WHERE prod_id = ‘RGA01‘);
在SELECT语句中,子查询总是从内向外处理。
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 = ‘RGA01‘));
只能是单列:作为子查询的SELECT语句只能查询单个列。企图检索多个列将返回错误。
为了对每个客户执行COUNT(*),应该将它作为一个子查询。
SELECT cust_name,cust_state,
(SELECT COUNT(*)
FROM Orders
WHERE Orders.cust_id = Customers.cust_id) AS orders
FROM Customers
ORDER BY cust_name;
原文地址:http://blog.csdn.net/veno813/article/details/45076227