• 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;

  • 相关阅读:
    日报9.4
    日报9.3
    低级错误整理
    树状数组求逆序对 笔记与思路整理
    st表、树状数组与线段树 笔记与思路整理
    Luogu P1098 字符串的展开
    Luogu P1816 忠诚
    jmeter cookie管理器 使用方法---新手学习记录1
    kali nessus 安装插件失败解决方法
    https tomcat 证书搭建
  • 原文地址:https://www.cnblogs.com/television/p/8353629.html
Copyright © 2020-2023  润新知