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;

  • 相关阅读:
    组合模式
    装饰者模式
    桥接设计模式
    Docker介绍
    适配器模式
    设计软件下载
    17种设计字体的创意方法
    less编译(mac版gulp)
    50种常用快捷键整理
    WebStorm设置手机测试服务器-局域网内其他设备访问
  • 原文地址:https://www.cnblogs.com/television/p/8353629.html
Copyright © 2011-2022 走看看