exists

2022-08-21 14:02:19 浏览数 (3)

我们可以使用exists代替in查询:

阿里编码规约第五条第(三)条第9条:

  1. 【推荐】in操作能避免则避免,若实在避免不了,需要仔细评估in后边的集合元素数量,控制在1000个之内。

我们可以在子元素多的情况下,使用exists查询

比如下面这个in查询

代码语言:javascript复制
SELECT
	* 
FROM
	sys_user AS a 
WHERE
	id in (
	SELECT
		user_id
	FROM
		sys_user_role AS b 
	WHERE
		b.role_id IN ( SELECT id FROM sys_role AS c WHERE b.role_id = c.id AND c.role_code LIKE '%o%' ));

可以改为:

代码语言:javascript复制
SELECT
	* 
FROM
	sys_user AS a 
WHERE
	EXISTS (
	SELECT
		user_id
	FROM
		sys_user_role AS b 
	WHERE
	a.id = b.user_id 
	AND EXISTS ( SELECT id FROM sys_role AS c WHERE b.role_id = c.id AND c.role_code LIKE '%o%' ));

0 人点赞