当前位置:Gxlcms > 数据库问题 > SQL连接、合并、子查询

SQL连接、合并、子查询

时间:2021-07-01 10:21:17 帮助过:2人阅读

-> > -> (select id,time from exam where id=1); +----+------------+-----------------+---------+--------+ | id | time | process | name | result | +----+------------+-----------------+---------+--------+ | 1 | 2016-08-31 | wait for result | baidu | 1 | | 2 | 2016-08-25 | haha | tengxun | 1 | | 3 | 2016-08-31 | jiayou | wangyi | 1 | | 9 | 2016-08-31 | happy | wangyi | 1 | +----+------------+-----------------+---------+--------+ 4 rows in set (0.02 sec)

带有关键字In的查询,当主查询的条件是子查询的查询结果中时,就可以通过关键字in来判断。相反如果不是可以用not in。

select * from table_name
where field_name in
(select field_name from table_name);

带有关键字ANY的查询:

=ANY:功能与in一样。

>ANY: 返回比子查询中最小的还要大的记录。只要大于子查询中其中一个就行了。

<ANY:返回比子查询中最大的还要小的记录。只要小于一个就行了。

带有关键字ALL的查询:

>ALL:比最大的还要大。

<ALL:比最小的还要小。

带有关键字exists

exist的子查询实际上不返回任何记录,而是返回true和false,如果子查询存在至少一条记录,就会返回true。否则就是false.

问题1:

 

--users表有1000条记录,id自增,id都大于0

select * from users where exists (select * from users limit 0); --输出多少条记录?

select * from users where exists (select * from users where id < 0); --输出多少条记录?

答案(请选中查看):

10000条

0条

 原因:

exists查询的本质,只要碰到有记录,则返回true;所以limit根本就不会去管,或者说执行不到。

 

问题2:

exists可以完全代替in吗?

不能。

例如:

--没有关联字段的情况:枚举常量

select * from areas where id in (4, 5, 6);

--没有关联字段的情况:这样exists对子查询,要么全true,要么全false

select * from areas where id in (select city_id from deals where deals.name = ‘xxx‘); 

 

SQL连接、合并、子查询

标签:

人气教程排行