SQL中的EXISTS关键字相关例子

今天在C++课的时候,看了几个关于EXISTS 关键字的学习视频,发现EXISTS本身这个知识点其实并不困难,但难点在于它的EXISTS中继续套一层exists.那么本博文就从自身的角度去浅谈如何理解EXISTS。

1.EXISTS 子查询的语法

在一般教科书当中,EXISTS子查询的相关语法

SELECT ... FROM 表名 WHERE EXISTS(子查询)
  • 子查询有返回结果:EXISTS子查询结果为TRUE
  • 子查询无返回结果: EXISTS子查询结果为FALSE 外层查询不执行

2. 数据表用例

2.1cities表

在这里插入图片描述

2.2 stores表

在这里插入图片描述

2.3 cities_stores表

在这里插入图片描述

2.4 分析表数据

我想在进入演示案例的时候,先分析数据表.cities表数据中主要存放,各种城市的名称。
在这里插入图片描述
然后我们再分析一下sores数据表,stores数据表中主要存放各种门店,还有门店类型。
在这里插入图片描述
最后就是城市开了的门店.比如apple在London、newyork看了很多门店。
在这里插入图片描述
那么就有了查询了,

3 查询案例

3.1 案例1:一个或多个城市有什么商店类型

比如 New York有哪些门店 ,需要门店的i名字和类型。肯定要有连接,需要将城市里的cities_stores里的store_type与stores里的store_type进行连接,如果进行连接后,我们就有了相关城市和商店类型的编号,最后进行stores的显示.

select distinct * from stores
where exists(
	select * from cities_stores
	where cities_stores.store_type = stores.store_type); 

在这里插入图片描述

3.2 案例2:一个或多个城市没有什么商店类型

select distinct * from stores
where  not exists(
	select * from cities_stores
	where cities_stores.store_type = stores.store_type); 

在这里插入图片描述

3.3 案例3:所有城市都有什么商店类型

那就需要将stores、cities进行全部连接

select distinct * from stores
where not exists(
	select * from cities where not exists(
		select * from cities_stores 
			where cities_stores.city = cities.city and 
			cities_stores.store_type = stores.store_type
	)
);

4.总结

EXISTS很多时候都是配合连接进行查询。EXISTS子句子查询有结果,那么我们就继续,如果没有结果就不继续。而更深入的使用,就需要对自连接、外连接、内连接搞得很熟才行。数据库是一门实践性很强的学科,需要课下不断努力训练。

Guess you like

Origin blog.csdn.net/m0_37149062/article/details/121262430