Day-10:使用子查询

1、子查询:嵌套在其他查询中的查询(mysql4.1版本引入子查询,以前版本不支持)

查询:任何SQL语句都是查询,但此术语一般指select语句。select语句是简单查询,即从单个数据库表中检索数据的单条语句。

2、利用子查询进行过滤

  例子:列出订购物品RGAN01的所有顾客

  分析:

    (1)检索包含物品BGAN01的所有订单编号

    (2)检索满足前一步列出的订单编号的所有顾客的ID

    (3)检索满足前一步返回所有顾客ID的顾客信息

  上面每一个步骤都可以单独作为一个查询来执行,可以把一条select语句返回的结果用于另一条select语句的where子句。

  也可以使用子查询来把3个查询组合成一条语句。

  步骤(1)查出RGAN01的所有订单编号

select order_num
from orderitems

where prod_id = 'RGAN01';
/*
order_num
20007
20008
*/

  步骤(2)通过订单编号查出顾客ID

select cust_id
from orders
where order_num in (20007, 20008);
#where order_num = 20007 or order_num = 20008;

/*
cust_id
1000000004
1000000005
*/

  把步骤1和2结合,第一个子句变为子查询,在select语句中,子查询都是从内向外处理的。

select cust_id
from orders
where order_num in (select order_num
                    from orderitems
                    where prod_id = 'RGAN01');

/*
cust_id
1000000004
1000000005
*/

  步骤(3)通过顾客ID查出顾客信息

select cust_name, cust_contact
from customers
where cust_id in ('1000000004','1000000005');

/*
cust_name, cust_contact
Fun4All    Denise L. Stephens
The Toy Store    Kim Howard
*/

  (1)、(2)和(3)结合

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'));

/*
cust_name, cust_contact
Fun4All    Denise L. Stephens
The Toy Store    Kim Howard
*/

说明:作为子查询的select语句只能查询单个列。

3、作为计算字段使用子查询

查询customers表中每个顾客的订单总数,

  (1)从customers表中查出顾客列表

  (2)统计每个顾客在orders表中的订单数目

select cust_name,
       cust_state,
       (select count(*)
        from orders
        where orders.cust_id = customers.cust_id) as orders
from customers
order by cust_name;

/*
cust_name cust_state orders
Fun4All        IN    1
Fun4All        AZ    1
Kids Place      OH    0
The Toy Store     IL    1
Village Toys      MI    2
*/
原文地址:https://www.cnblogs.com/jp-mao/p/6574411.html