mysql浅析

[实战]mysql子查询

2022-04-02  本文已影响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;

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

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

SELECT … FROM table WHERE EXISTS (subquery)

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

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

上一篇 下一篇

猜你喜欢

热点阅读