美文网首页mysql浅析
[实战]mysql子查询

[实战]mysql子查询

作者: 超鸽带你飞 | 来源:发表于2022-04-02 15:23 被阅读0次

联合查询

将多条select语句记录上拼接
语法:

select 语句1
union [union选项]
select 语句2….

[union选项]
- All (不去重)
- distinct (默认)

order by 使用 -- 必须配合limit才能生效,并且()

(select 语句1 order by.. limit.. )
union [union选项]
(select 语句1 order by ..limit.. )

子查询

查询实在某个查询结果之上.

  • 按位置分类:
1\. from 子查询

2\. where 子查询

3\. exists 子查询
  • 按结果分类
  1.标量子查询    -- 一列一行
  2.列子查询      -- 一列多行
  3.行子查询      -- 多列一行
      ***以上的位置在where之后***
  4.表子查询      -- 多列多行  出现的位置在from后

举例

student表

image.png

class表
id | name

  • 标量子查询:

select * from student where c_id = (select id from class where name='php100’)

  • 列子查询:

select * from student where c_id in (select id from class) ;

  • 行子查询:

SELECT * FROMstudentWHERE (age,height) = (SELECT max(age),max(height) FROM student);

  • 表子查询:

需求:查询每个班最高的学生。

(错误用法 )select * from student group by c_id order by height DESC;

(正确用法 )select * from (select * from student order by height DESC ) as my_student group by c_id;

  • exists子查询:

需求:查询所有在读班级的学生

select * from student where exists(select * from class where student.c_id=class.id)

  • exists子查询:【讲解】

SELECT … FROM table WHERE EXISTS (subquery)

该语法可以理解为:将主查询的数据,放到子查询中做条件验证,根据验证结果(TRUE 或 FALSE)来决定主查询的数据结果是否得以保留。

exists对外表用loop逐条查询,每次查询都会查看exists的条件语句,当 exists里的条件语句能够返回记录行时(无论记录行是的多少,只要能返回),条件就为真,返回当前loop到的这条记录,反之如果exists里的条 件语句不能返回记录行,则当前loop到的这条记录被丢弃,exists的条件就像一个bool条件,当能返回结果集则为true,不能返回结果集则为 false

相关文章

  • MySQL实战5 子查询

    MySQL实战 目录 子查询介绍:出现在其他语句中的select语句,被包裹的select语句就是子查询或查询包裹...

  • MySQL实战 目录

    MySQL实战 MySQL实战1 数据库概念介绍MySQL实战2 语法、筛选条件和函数MySQL实战3 分组查询和...

  • [实战]mysql子查询

    联合查询 将多条select语句记录上拼接语法: 子查询 查询实在某个查询结果之上. 按位置分类: 按结果分类 举...

  • MySQL 子查询、内联结、外联结

    子查询MySQL 子查询版本要求:MySQL4.1引入了对子查询的支持。子查询:嵌套在其他查询语句中的查询。 示例...

  • mysql 查询

    mysql的查询、子查询及连接查询 一、mysql查询的五种子句 where(条件查询)、having(筛选)、g...

  • 【MySQL】MySQL查询——子查询

    查出本网站,最新的(goods_id最大)的商品select goods_id,goods_name,cat_id...

  • 第六章 查询性能优化(下)

    MySQL查询优化器的局限性 关联子查询 MySQL的关联子查询实现的很差,最好改成左外连接(LEFT OUTER...

  • 查询性能优化

    MySQL查询优化器的局限性 关联子查询 MySQL的子查询实现的非常糟糕,最糟糕的一类查询是where条件中包含...

  • MySql查询-子查询

    子查询 在一个 select 语句中,嵌入了另外一个 select 语句, 那么被嵌入的 select 语句称之为...

  • 深入学习MySQL优化

    MySQL高性能优化实战总结 MySQL 的查询过程如下图,很多的查询优化工作实际上就是遵循一些原则。 优化的哲学...

网友评论

    本文标题:[实战]mysql子查询

    本文链接:https://www.haomeiwen.com/subject/hovtsrtx.html