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

    一、子查询的分类

      1. 按位置分为

        where 子查询:子查询在where条件中

        from 子查询:子查询在from后面

        exists子查询:子查询在exists中

      2. 按查询结果分为

        标量子查询:查询结果有一行一列

        列子查询:查询结果有一列多行

        行子查询:查询结果有一行多列或多行多列

        表子查询:查询结果有多行多列并且出现的位置在from之后

    二、子查询详解

      1. 标量子查询

        -- 已知学生表my_stu和班级表my_class, 查询class001班中的所有学生,查询结果是一个ID,一行和列

        select * from my_stu where class_id = (select id from my_class where c_name = 'class001');

      2. 列子查询

        -- 查询所有存在的班级内的学生

        select * from my_stu where class_id in (select id from my_class);

        -- 类似in的其他条件关键字, 都必须带 = 号

        select * from my_stu where class_id = any(select id from my_class);  -- 等于其中任意一个就保留

        select * from my_stu where class_id = some(select id from my_class); -- 等于其中一部分就保留

        select * from my_stu where class_id = all (select id from my_class);   -- 等于其中所有的才保留

      3. 行子查询

        -- 查询学生中年龄最大且身高最高的

        select * from my_stu where age = (select max(age) from my_stu) and height = (select max(height) from my_stu);  -- 常规查询

        select * from my_stu where (age,height) = (select max(age),max(height) from my_stu);  -- 构造行元素来使用行子查询

      4. 表子查询

        -- 找出每个班最高的一个学生

        select * from (select * from my_stu order by height desc) as s group by class;

      5. exists子查询

        exists接在where之后, 返回0或1.

        select * from my_student where exists(select * from my_class where id = 1);

  • 相关阅读:
    .net开发微信公众号(2)-验证服务器地址
    [广度遍历和深度遍历]聊聊算法和设计模式
    DDD领域驱动设计之聚合、实体、值对象
    DDD领域驱动设计之运用层代码
    DDD领域驱动设计之领域服务
    DDD领域驱动设计之领域基础设施层
    DDD领域驱动设计实践篇之如何提取模型
    Docker最全教程——从理论到实战(七)
    Docker最全教程——从理论到实战(六)
    Docker最全教程——从理论到实战(五)
  • 原文地址:https://www.cnblogs.com/pengyin/p/6379855.html
Copyright © 2011-2022 走看看