PostgreSQL之SEMI-JOIN半连接

什么是Semi-Join半连接

Semi-Join半连接,当外表在内表中找到匹配的记录之后,Semi-Join会返回外表中的记录。但即使在内表中找到多条匹配的记录,外表也只会返回已经存在于外表中的记录。而对于子查询,外表的每个符合条件的元组都要执行一轮子查询,效率比较低下。此时使用半连接操作优化子查询,会减少查询次数,提高查询性能。其主要思路是将子查询上拉到父查询中,这样内表和外表是并列关系,外表的每个符合条件的元组,只需要在内表中找符合条件的元组即可,所以效率会大大提高。

1

当参与等值JOIN表达式存在有重复值时, 如果不需要找出该表其他字段的值(也就是仅使用JOIN字段/表达式), 那么JOIN时只需要查每个值的第一条, 然后就可以跳到下一个值. 在数据库中常常被用来优化 in, exists, not exists, = any(), except 等操作(或者逻辑上成立的其他JOIN场景).

还有什么特别的join?PostgreSQL 与关系代数 (Equi-Join , Semi-Join , Anti-Join , Division)

并不是所有数据库都实现了所有场景的semi join, 例如 Oracle中的半连接,MySQL也有半连接

如果未实现, 有什么方法可以模拟semi-join?递归/group by/distinct on/distinct

Semi-Join 例子

准备测试数据

postgres=# create table a (id int, info text, ts timestamp);  
CREATE TABLE  
postgres=# create table b (like a);  
CREATE TABLE  
postgres=# insert into a select id, md5(random()::text), now() from generate_series(0,1000000) as t(id);  
INSERT 0 1000001  -- b表的100万行记录中b.id只有11个唯一值  
postgres=# insert into b select random()*10, md5(random()::text), now() from generate_series(0,1000000) as t(id);  
INSERT 0 1000001  postgres=# create index on a (id);  
CREATE INDEX  
postgres=# create index on b (id);  
CREATE INDEX

未优化SQL

select a.* from a where exists (select 1 from b where a.id=b.id);  postgres=# explain analyze select a.* from a where exists (select 1 from b where a.id=b.id);  QUERY PLAN                                                                       
----------------------------------------------------------------------------------------------------------------------------------------------------  Merge Join  (cost=18436.17..18436.66 rows=11 width=45) (actual time=226.590..226.598 rows=11 loops=1)  Merge Cond: (a.id = b.id)  ->  Index Scan using a_id_idx on a  (cost=0.42..27366.04 rows=1000001 width=45) (actual time=0.010..0.013 rows=12 loops=1)  ->  Sort  (cost=18435.74..18435.77 rows=11 width=4) (actual time=226.576..226.577 rows=11 loops=1)  Sort Key: b.id  Sort Method: quicksort  Memory: 25kB  ->  HashAggregate  (cost=18435.44..18435.55 rows=11 width=4) (actual time=226.568..226.570 rows=11 loops=1)  Group Key: b.id  Batches: 1  Memory Usage: 24kB  ->  Index Only Scan using b_id_idx on b  (cost=0.42..15935.44 rows=1000001 width=4) (actual time=0.010..77.936 rows=1000001 loops=1)  Heap Fetches: 0  Planning Time: 0.189 ms  Execution Time: 226.630 ms  
(13 rows)

以上查询没有使用semi-join, 性能很一般.

由于b表的100万行记录中b.id只有11个唯一值, 可以使用semi-join进行加速.

用法参考: 《用PostgreSQL找回618秒逝去的青春 - 递归收敛优化》

使用递归模拟SEMI-JOIN, 只需要 0.171 ms 既可得出b表 11个值的结果.

with recursive tmp as (  select min(id) as id from b   union all   select (select min(b.id) from b where b.id > tmp.id) from tmp where tmp.id is not null  
)   
select * from tmp where tmp.id is not null;  id   
----  0  1  2  3  4  5  6  7  8  9  10  
(11 rows)

执行计划如下

postgres=# explain analyze with recursive tmp as (  select min(id) as id from b   union all   select (select min(b.id) from b where b.id > tmp.id) from tmp where tmp.id is not null  
)   
select * from tmp where tmp.id is not null;  QUERY PLAN                                                                            
--------------------------------------------------------------------------------------------------------------------------------------------------------------  CTE Scan on tmp  (cost=50.07..52.09 rows=100 width=4) (actual time=0.028..0.134 rows=11 loops=1)  Filter: (id IS NOT NULL)  Rows Removed by Filter: 1  CTE tmp  ->  Recursive Union  (cost=0.44..50.07 rows=101 width=4) (actual time=0.025..0.126 rows=12 loops=1)  ->  Result  (cost=0.44..0.45 rows=1 width=4) (actual time=0.024..0.025 rows=1 loops=1)  InitPlan 3 (returns $1)  ->  Limit  (cost=0.42..0.44 rows=1 width=4) (actual time=0.021..0.022 rows=1 loops=1)  ->  Index Only Scan using b_id_idx on b b_1  (cost=0.42..18435.44 rows=1000001 width=4) (actual time=0.020..0.020 rows=1 loops=1)  Index Cond: (id IS NOT NULL)  Heap Fetches: 0  ->  WorkTable Scan on tmp tmp_1  (cost=0.00..4.76 rows=10 width=4) (actual time=0.007..0.007 rows=1 loops=12)  Filter: (id IS NOT NULL)  Rows Removed by Filter: 0  SubPlan 2  ->  Result  (cost=0.45..0.46 rows=1 width=4) (actual time=0.007..0.007 rows=1 loops=11)  InitPlan 1 (returns $3)  ->  Limit  (cost=0.42..0.45 rows=1 width=4) (actual time=0.006..0.006 rows=1 loops=11)  ->  Index Only Scan using b_id_idx on b  (cost=0.42..6979.51 rows=333334 width=4) (actual time=0.006..0.006 rows=1 loops=11)  Index Cond: ((id IS NOT NULL) AND (id > tmp_1.id))  Heap Fetches: 0  Planning Time: 0.177 ms  Execution Time: 0.171 ms  
(23 rows)

使用递归模拟semi-join, SQL改写如下:

select a.* from a where exists (select 1 from b where a.id=b.id);  改写成  select a.* from a where exists (select 1 from   
(  
with recursive tmp as (  select min(id) as id from b   union all   select (select min(b.id) from b where b.id > tmp.id) from tmp where tmp.id is not null  
)   
select * from tmp where tmp.id is not null  
) b  where a.id=b.id);

改写后速度从226.630 ms 提升到 0.246 ms

postgres=# explain analyze select a.* from a where exists (select 1 from   
(  
with recursive tmp as (  select min(id) as id from b   union all   select (select min(b.id) from b where b.id > tmp.id) from tmp where tmp.id is not null  
)   
select * from tmp where tmp.id is not null  
) b  where a.id=b.id);  QUERY PLAN                                                                                  
--------------------------------------------------------------------------------------------------------------------------------------------------------------------------  Nested Loop  (cost=53.76..318.49 rows=100 width=45) (actual time=0.154..0.189 rows=11 loops=1)  ->  HashAggregate  (cost=53.34..54.34 rows=100 width=4) (actual time=0.144..0.149 rows=11 loops=1)  Group Key: tmp.id  Batches: 1  Memory Usage: 24kB  ->  CTE Scan on tmp  (cost=50.07..52.09 rows=100 width=4) (actual time=0.027..0.139 rows=11 loops=1)  Filter: (id IS NOT NULL)  Rows Removed by Filter: 1  CTE tmp  ->  Recursive Union  (cost=0.44..50.07 rows=101 width=4) (actual time=0.024..0.130 rows=12 loops=1)  ->  Result  (cost=0.44..0.45 rows=1 width=4) (actual time=0.023..0.024 rows=1 loops=1)  InitPlan 3 (returns $1)  ->  Limit  (cost=0.42..0.44 rows=1 width=4) (actual time=0.020..0.021 rows=1 loops=1)  ->  Index Only Scan using b_id_idx on b b_1  (cost=0.42..18435.44 rows=1000001 width=4) (actual time=0.019..0.019 rows=1 loops=1)  Index Cond: (id IS NOT NULL)  Heap Fetches: 0  ->  WorkTable Scan on tmp tmp_1  (cost=0.00..4.76 rows=10 width=4) (actual time=0.008..0.008 rows=1 loops=12)  Filter: (id IS NOT NULL)  Rows Removed by Filter: 0  SubPlan 2  ->  Result  (cost=0.45..0.46 rows=1 width=4) (actual time=0.007..0.007 rows=1 loops=11)  InitPlan 1 (returns $3)  ->  Limit  (cost=0.42..0.45 rows=1 width=4) (actual time=0.006..0.006 rows=1 loops=11)  ->  Index Only Scan using b_id_idx on b  (cost=0.42..6979.51 rows=333334 width=4) (actual time=0.006..0.006 rows=1 loops=11)  Index Cond: ((id IS NOT NULL) AND (id > tmp_1.id))  Heap Fetches: 0  ->  Index Scan using a_id_idx on a  (cost=0.42..2.63 rows=1 width=45) (actual time=0.003..0.003 rows=1 loops=11)  Index Cond: (id = tmp.id)  Planning Time: 0.295 ms  Execution Time: 0.246 ms  
(29 rows)

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/614961.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

GitLab 502 Whoops, GitLab is taking too much time to respond. 解决

1、先通过gitlab-ctl restart进行重启,2分钟后看是否可以正常访问,为什么要2分钟,因为gitlab启动会有很多配套的服务启动,包括postgresql等 2、如果上面不行,再看gitlab日志,通过gitlab-ctl tail命令查看&…

【Arduino】编程语言:定时函数、数学函数、字符函数(功能、语法格式、参数说明、返回值) | 软件开发环境:安装步骤介绍(EXE安装版、ZIP安装版)

你的负担将变成礼物,你受的苦将照亮你的路。———泰戈尔 🎯作者主页: 追光者♂🔥 🌸个人简介: 💖[1] 计算机专业硕士研究生💖 🌿[2] 2023年城市之星领跑者TOP1(哈尔滨)🌿 🌟[3] 2022年度博客之星人工智能领域TOP4🌟 🏅[4] 阿里云社区…

再发一波微信红包封面,免费!免费!免费!

我是90后程序员,大家都叫我小码哥,从事互联网近10余年了,一直想在互联网上分享自己的管理经验和技术经验,同时也想找一些志同道合的朋友,一起聊聊如何从互联网中快速的成长起来,无论是通过技术、互联网风口…

谈谈曲线与曲面

目录 1、非参数曲线与曲面 2、方程式曲线与曲面 3、参数曲线与曲面 3.1平面参数曲线 3.2空间参数曲线 3.3参数曲面 1、非参数曲线与曲面 非参数曲线曲面是一种与参数曲线曲面相对的概念。在非参数方法中,曲线或曲面不是通过参数方程来定义的,而是通…

【AI视野·今日Robot 机器人论文速览 第七十二期】Mon, 8 Jan 2024

AI视野今日CS.Robotics 机器人学论文速览 Mon, 8 Jan 2024 Totally 13 papers 👉上期速览✈更多精彩请移步主页 Daily Robotics Papers Deep Reinforcement Learning for Local Path Following of an Autonomous Formula SAE Vehicle Authors Harvey Merton, Thoma…

ubuntu 22.04源码装ros1 noetic

ubuntu 22.04源码装ros1 noetic 文章目录 ubuntu 22.04源码装ros1 noetic1. 安装依赖2. 更换rosdep相关的rep链接3. 安装 rosdep4. 创建工作空间下载源码并安装5. 编译代码5.1 修复rosconsole* log相关问题**error**5.3 python-sip配置相关5.4 *std::share_mutex* 相关 c11 与c…

算法通关村番外篇-跳表

大家好我是苏麟 , 今天来聊聊调表 . 跳表很少很少实现所以我们只了解就可以了 . 跳表 链表在查找元素的时候,因为需要逐一查找,所以查询效率非常低,时间复杂度是O(N),于是就出现了跳表。跳表是在链表基础上改进过来的&#xff0…

OpenCV——图像按位运算

目录 一、算法概述1、逻辑运算2、函数解析3、用途 二、代码实现三、结果展示 OpenCV——图像按位运算由CSDN点云侠原创,爬虫自重。如果你不是在点云侠的博客中看到该文章,那么此处便是不要脸的爬虫。 一、算法概述 1、逻辑运算 OpenCV4 针对两个图像之…

JDBC初体验(二)——增、删、改、查

本课目标 理解SQL注入的概念 掌握 PreparedStatement 接口的使用 熟练使用JDBC完成数据库的增、删、改、查操作 SQL注入 注入原理:利用现有应用程序,将(恶意的)SQL命令注入到后台数据库引擎执行能力,它可以通过在…

银河麒麟v10安装前端环境(Node、vue、Electron+vite)

此帖子所提到的所有依赖包都是基于银河麒麟v10真机的arm架构包,如果是在windows上的虚拟机上 把依赖包换成x64的包即可,方法步骤都是一样 一.node安装 原始方法安装(建议用第二种nvm方法,因为更简单): 1…

基于Docker官方php:5.6.40-fpm镜像构建支持66个常见模组的php5.6.40镜像

实践说明:基于RHEL7(CentOS7.9)部署docker环境(23.0.1、24.0.2),所构建的php5.6.40镜像应用于RHEL7-9(如AlmaLinux9.1),但因为docker的特性,适用场景是不限于此的。 文档形成时期:2017-2023年 因系统或软件版本不同&am…

工业异常检测AnomalyGPT-训练试跑及问题解决

写在前面,AnomalyGPT训练试跑遇到的坑大部分好解决,只有在保存模型失败的地方卡了一天才解决,本来是个小问题,昨天没解决的时候尝试放弃在单卡的4090上训练,但换一台机器又遇到了新的问题,最后决定还是回来…

图像识别与计算机视觉有什么区别?

图像识别和计算机视觉在很多方面存在差异,这些差异主要体现在以下几个方面: 1. 研究范围 图像识别是计算机视觉领域的一个子集。计算机视觉不仅包括图像识别,还涵盖了更广泛的内容,如场景理解、目标跟踪、分割、识别和解释等。简而…

Android12 关机流程

Android12 关机流程 Android 关机流程的意义在于确保系统可以安全地关闭,并且所有用户数据得到妥善保存,以防止数据丢失和损坏。 Android 关机流程确保系统可以安全地关闭,并且所有用户数据得到妥善保存。 保存用户数据:在 Android 关机过程中,系统会通知应用程序和服务进…

jsPlumb、mxGraph和Antv x6实现流程图选型

解决方案 结合我们项目以及主流解决方案,提供以下几种方案: 序号技术栈性质是否开源说明1jsPlumb国外框架社区版、商业版中台项目现有方案2mxGraph国外框架开源比较有名的开源绘图网站draw.io (和processOn类似),使用…

力扣48. 旋转图像

几何翻转 思路: 顺时针旋转可以拆解成: 先沿着水平中轴线进行翻转: m[i][j] -> m[n - 1 - i][j] (x1 x2) / 2 (n - 1) / 2x1 (n - 1) - x2y 轴不变沿着主对角线进行翻转: m[i][j] -> m[j][i] class Solution { public:…

https 中 ssl/tls 的握手

如果使用了 https 协议,那么在建立 tcp 连接之后,还会进行 tls 握手。也就是 https 的证书验证和密钥传输的过程。简化的流程如下: 客户端发送请求服务端返回证书客户端验证证书,提取公钥,生成对称加密的密钥&#xf…

JavaScript基础02

1 - 运算符(操作符) 1.1 运算符的分类 运算符(operator)也被称为操作符,是用于实现赋值、比较和执行算数运算等功能的符号。 JavaScript中常用的运算符有: 算数运算符 递增和递减运算符 比较运算符 逻…

GBASE南大通用系统目录表

系统目录由描述数据库结构的表和视图组成。这些表对象有时称为数据字典,它们包含 数据库本身的所有信息。每个系统目录表都包含有关数据库中特定元素的信息。每个数据 库都有它自己的系统目录。 这些主题提供了有关系统目录表的结构、内容和使用的信息。还包含了有关…

第五站:C++的内存解析

目录 C内存分布 变量的四种存储方式 函数返回值使用指针(指针函数) 动态分配内存空间 不能使用外部函数的普通局部变量的地址 通过指针函数返回静态局部变量的地址 动态内存 根据需要分配内存,不浪费(根据用户的需求设置内存的容量) 被调用函数之外需要使用被调用函数内…