Mysql any、some、in、all、exists 关键字

1,738 阅读3分钟
mysql> select * from test;
+----+--------+------+------+
| id | name   | sex  | age  |
+----+--------+------+------+
|  1 | name1  ||   15 |
|  2 | name1  ||   15 |
|  4 | name2  ||   30 |
|  5 | name50 ||   12 |
+----+--------+------+------+
  • in 关键字
in 关键字在子查询中主要用在列子查询中代替人为手罗列出来的多个“字面值”数据。

举例:
select * from 表名 where 地区 in ('上海', '北京', ...);
select * from 表名 where 地区 in (select 地区列表 from 地图表数据);
  • any关键字
any 可以与(=>>=<<=<>)结合起来使用,分别表示等于、大于、大于等于、小于、小于等于、不等于其中的任何一个数据。

any 关键字用在比较操作符(=>>=<<=<>...)的后面,表示查询结果的多个数据中的任一个满足该比较操作符就算满足。

语法形式:
select * from 表名 where 字段名=any(必须为子查询);
结果相当于:
select * from 表名 where 字段名=1 or 字段名=2 or 字段名=3 or ...;

注意:any()括号不可以写成固定值,必须为子查询,这种写法是错误的:
select * from 表名 where 字段名=any(1, 2, 3);

举例:
select * from 表名 where 字段名=any(select 字段名 from 表名);
  • some关键字
some 的作用与使用跟 any 一样,两者没差别
  • all 关键字
all 可以与(=>>=<<=<>)结合是来使用,分别表示等于、大于、大于等于、小于、小于等于、不等于其中的其中的所有数据。

all 关键字用在比较操作符(=>>=<<=<>...)的后面,表示查询结果的多个数据中的所有都满足该比较操作符才算满足。

语法形式:
select * from 表名 where 字段名>all(必须为子查询);
结果相当于:
select * from 表名 where 字段名>1 and 字段名>2 and 字段名>3 and ...;

注意:all()括号不可以写成固定值,必须为子查询,这种写法是错误的:
select * from 表名 where 字段名>all(1, 2, 3);

举例:
select * from 表名 where 字段名>all(select 字段名 from 表名);
  • exists 关键字
含义:
该子查询如果“有数据”则该 exists() 的结果为 "true" 即相当于 where true。
该子查询如果“没有数据”则该 exists() 的结果为 "false" 即相当于 where false。

语法形式:
select * from 表名 where exists(任何子查询);

举例:
两个表:商品信息表(包含商品类型ID)  商品类型表(电器类、日常用品类)
查询出商品类型名称带 "电" 字的所有商品信息
select * from 商品信息表 where exists (select * from 商品类型表 like '%电%' and 商品信息表.商品类型ID = 商品类型表.商品类型ID)
如果表里面有大于30岁的则显示列出所有数据
mysql> select * from test where exists(select * from test where age>30);
Empty set (0.00 sec)

如果表里面有大于15岁的则显示列出所有数据
mysql> select * from test where exists(select * from test where age>15);
+----+--------+------+------+
| id | name   | sex  | age  |
+----+--------+------+------+
|  1 | name1  ||   15 |
|  2 | name1  ||   15 |
|  4 | name2  ||   30 |
|  5 | name50 ||   12 |
+----+--------+------+------+

mysql> select * from test as t1 where exists(select * from test as t2 where t2.age>15 and t1.age > 15);
+----+-------+------+------+
| id | name  | sex  | age  |
+----+-------+------+------+
|  4 | name2 ||   30 |
+----+-------+------+------+

mysql> select * from test as t1 where exists(select * from test as t2 where t1.age > 15);
+----+-------+------+------+
| id | name  | sex  | age  |
+----+-------+------+------+
|  4 | name2 ||   30 |
+----+-------+------+------+