1 子查询
即嵌套在其他查询中的查询。MySQL从4.1版本才支持
2 利用子查询进行过滤
举例说明:列出订购物品 RGAN01 的所有顾客。
(1) 检索包含物品 RGAN01 的所有订单的编号。
(2)检索具有前一步骤列出的订单编号的所有顾客的ID。
(3)检索前一步骤返回的所有顾客ID的顾客信息。
第一条:SELECT order_num FROM orderitems WHERE prod_id = 'RGAN01';
1.png
第二条:SELECT cust_id FROM orders WHERE order_num IN (20007,20008);
2.png
结合这两个查询,把第一个查询变为子查询:SELECT cust_id FROM orders WHERE order_num IN (SELECT order_num FROM orderitems WHERE prod_id = 'RGAN01');
1+2.png
在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 = 'RGAN01'));
3.png
注意:作为子查询的SELECT语句只能查询单个列。
3 作为计算字段使用子查询
举例说明:列出Customers表中每个顾客的订单总数。SELECT cust_name,cust_state,(SELECT COUNT(*) FROM orders WHERE orders.cust_id=customers.cust_id) AS orsers FROM customers ORDER BY cust_name
4.png
作者:Love零O
链接:https://www.jianshu.com/p/7c7c9b2fbc72
共同學習,寫下你的評論
評論加載中...
作者其他優質文章