Mysql exists用法小结

简介

exists用于检查子查询是否至少会返回一行数据,该子查询实际上并不返回任何数据,而是返回值true或false。

exists 指定一个子查询,检测行的存在。语法:exists subquery。参数 subquery 是一个受限的 select 语句 (不允许有 compute 子句和 into 关键字)。结果类型为 boolean,如果子查询包含行,则返回 true。

示例

一张活动配置主表activity_main,通过act_code来唯一标明一场活动,活动举办地点适配表activity_area,通过act_code与主表进行关联,活动奖品表activity_sku,通过act_code与主表进行关联。

活动主表

create table `activity_main` (
`id` bigint(20) not null auto_increment,
`act_code` varchar(255) not null comment '活动代码',
`act_name` varchar(255) not null comment '活动名称',
primary key (`id`),
unique key `uniq_code` (`act_code`)
) engine=innodb auto_increment=1 default charset=utf8mb4 collate=utf8mb4_0900_ai_ci comment='活动主表'

活动在哪些网站举办的适配表

create table `activity_area` (
 `id` bigint(20) not null auto_increment,
 `act_code` varchar(255) not null comment '活动代码',
 `area` varchar(255) not null comment '参与此活动的网站',
 primary key (`id`)
) engine=innodb auto_increment=1 default charset=utf8mb4 collate=utf8mb4_0900_ai_ci comment='活动适配的网站列表'

活动奖品表

create table `activity_sku` (
 `id` bigint(20) not null auto_increment,
 `act_code` varchar(255) not null comment '活动代码',
 `sku` varchar(255) not null comment '活动赠送的商品',
 primary key (`id`)
) engine=innodb auto_increment=1 default charset=utf8mb4 collate=utf8mb4_0900_ai_ci comment='活动赠品表'

比较使用 exists 和 in 的查询
这个例子比较了两个语义类似的查询。第一个查询使用 in 而第二个查询使用 exists。注意两个查询返回相同的信息。

# 查询体重秤
select * from activity_main where act_code in (
select act_code from activity_sku where sku = '翎野君的体脂称'
)

# 查询体重秤
select * from activity_main a where exists (
select 1 from activity_sku b where a.act_code = b.act_code and b.sku = '翎野君的体脂称'
)

# 模糊查询b-beko英国婴儿推车
select * from activity_main where act_code in (
select act_code from activity_sku where sku like '%b-beko%'
)

# 模糊查询b-beko英国婴儿推车
select * from activity_main a where exists (
select 1 from activity_sku b where a.act_code = b.act_code and b.sku like '%b-beko%'
)

# 查询在博客园举办的活动
select * from activity_main where act_code in (
select act_code from activity_area where area = '博客园'
)

# 查询在博客园举办的活动
select * from activity_main a where exists (
select 1 from activity_area b where a.act_code = b.act_code and b.area = '博客园'
)


# 在博客园举办活动且活动奖品为华为手机的活动信息
select * from activity_main where act_code in (
select act_code from activity_area where area = '博客园' and act_code in (
select act_code from activity_sku where sku = '华为p30pro'
))


# 内层的exists语句只在当前where语句中生效,最终是否返回,要根据最外层的exists判断,如果是 true(真)就返回到结果集,为 false(假)丢弃。
select * from activity_main a where exists (
select 1 from activity_area b where a.act_code = b.act_code and b.area = '博客园' and exists
(select 1 from activity_sku c where a.act_code = c.act_code and c.sku = '华为p30pro')
)

以上就是mysql exists用法小结的详细内容,更多关于mysql exists用法的资料请关注www.887551.com其它相关文章!

(0)
上一篇 2022年3月21日
下一篇 2022年3月21日

相关推荐