zoukankan      html  css  js  c++  java
  • mysql-子查询

    一、一般子查询

      SQL还允许创建子查询,即嵌套在其他查询中的查询。使用in关键字。

      我们可以使用子查询把若干个查询组合成一条语句,使其结果变得可控。

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

      上述语句的含义是:需要列出订购物品TNT2的所有客户。

      在select语句中,子查询总是从内向外处理,在处理上面的select语句时,mysql实际上是执行了三个操作。

      1、select order_num from orderitems where prod_id='TNT2';

      2、select cust_id from oreders where order_num in(20005,20007);

      3、select cust_name,cust_contact from customers where cust_id in(100001,100004);

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

      虽然查询一般与in操作符结合使用,但也可以用于测试等于=不等于<>

      使用子查询的另一个方法是创建计算字段,假如需要显示customers表中每个客户的订单总数,订单与相应的客户的ID存储在orders表中。需要遵循以下操作:

      1、从customs表中检索客户列表

      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;

  • 相关阅读:
    923c C. Perfect Security
    hdu ACM Steps Section 1 花式A+B 输入输出格式
    我回来了
    POJ–2104 K-th Number
    bzoj1009: [HNOI2008]GT考试
    bzoj1875: [SDOI2009]HH去散步
    1898: [Zjoi2005]Swamp 沼泽鳄鱼
    Hadoop
    程序员的自我修养
    Effective C++笔记
  • 原文地址:https://www.cnblogs.com/television/p/8353629.html
Copyright © 2011-2022 走看看