Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

any、all、some 用法 #19

Open
astak16 opened this issue Jan 11, 2022 · 0 comments
Open

any、all、some 用法 #19

astak16 opened this issue Jan 11, 2022 · 0 comments

Comments

@astak16
Copy link
Owner

astak16 commented Jan 11, 2022

anyallsome 是子查询关键词之一,必须与一个比较操作符进行一起使用。

  • any 和子查询返回的列中 任一值 比较为 true 则返回为 true
  • all 和子查询返回的列中 所有值 比较为 true 则返回为 true
  • some 的用法和 any 一样,在 != 的场景中,用 any 容易产生误解,用 some 更容易理解
create table t1 (id int, value int);
create table t2 (id int, value int);

insert into t1 values(1, 10), (2, 300), (3, 40), (4, 60), (5, 70), (6, 80);
insert into t2 values(1, 100), (2, 300), (3, 40), (4, 600), (5, 70), (6, 800);

all 方法

select * from t1 where value <= all(
	select value from t2
);
  1. 子查询查出 t2 表中所有的 value ,结果为 (100, 300, 40, 600, 70, 800)
  2. t1 表中筛选 value <= all(100, 300, 40, 600, 70, 800)
    • 第一条数据的 value = 10 ,它小于等于 (100, 300, 40, 600, 70, 800) 里所有的值,结果为 true
    • 第二条数据的 value = 300 它没有小于等于 (100, 300, 40, 600, 70, 800) 里所有的值,结果为 false
    • 不断循环下去,直到最后查完所有数据

tips

  • 如果子查询中结果为 ,结果为 true
  • 如果有一条数据为 null ,结果为 false ,也就是说查不出结果
  • 如果有所有数据为 null ,结果为 false ,和结果为空不是一个概念

any 方法

select * from t1 where value <= any(
	select value from t2
);
  1. 子查询查出 t2 表中所有的 value ,结果为 (100, 300, 40, 600, 70, 800)
  2. t1 表中筛选 value <= (100, 300, 40, 600, 70, 800)
    • 第一条数据的 value = 10 ,它小于等于 (100, 300, 40, 600, 70, 800) 里任一的值,结果为 true
    • 第二条数据的 value = 300 它没有小于等于 (100, 300, 40, 600, 70, 800) 里任一的值,结果为 true
    • 不断循环下去,直到最后查完所有数据

tips:

  • 如果子查询中结果为 ,结果为 false,也就是说查不出结果
  • 如果子查询中所有结果都为 null ,结果为 false

some 用法

select * from t1 where value != some(
	select value from t2
);

t1 表中有部分 valuet2 表中的 value 不相等

如果用 any 就会理解成:t1 表中的 valuet2 表中的任意 value 不相等。

他们结果是一样的。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant