digoal
2024-05-03
PostgreSQL , PolarDB , DuckDB , Positional Joins
DuckDB的join支持非常丰富, 除了常用的inner join , outer join , 笛卡尔积等, 还支持 semi join , anti join , asof join , lateral join , positional join等.
参考文档:
https://duckdb.org/docs/sql/query_syntax/from
其中 asof join 通常用于解决业务无法满足等值精确JOIN匹配的数据关联问题、或者2张表的数据存在gap的问题, 例如IoT场景或日志场景.
《DuckDB 0.8.0 发布, 支持pivot语法, ASOF JOIN, 并行导入导出性能提升, 递归通配符解析文件, arrow 连接器等》
lateral join 则方便在join subquery里面取前面JOIN表的内容进行匹配或过滤的需求.
《PostgreSQL 9.3 add LATERAL support - LATERAL的语法和用法介绍》
semi join , anti join 简化了in , not in , exists , not exists 的写法.
《DuckDB semi join , anti join 语法糖》
本文主要分享Positional Joins 语法糖的使用, 两个表按row 位置ID进行JOIN, 如果两个表的记录数不一样, 记录数少的填充为NULL.
例子
create table a (id int, c1 int);
create table b (id int, c1 int, c2 int);
insert into a select id,random()*10 from range(0,10) t (id);
insert into b select id,random()*10,random()*10 from range(0,5) t (id);
查询
SELECT *
FROM a
POSITIONAL JOIN b;
返回
┌───────┬───────┬───────┬───────┬───────┐
│ id │ c1 │ id │ c1 │ c2 │
│ int32 │ int32 │ int32 │ int32 │ int32 │
├───────┼───────┼───────┼───────┼───────┤
│ 0 │ 10 │ 0 │ 1 │ 8 │
│ 1 │ 10 │ 1 │ 5 │ 2 │
│ 2 │ 9 │ 2 │ 0 │ 1 │
│ 3 │ 7 │ 3 │ 3 │ 0 │
│ 4 │ 10 │ 4 │ 8 │ 7 │
│ 5 │ 1 │ │ │ │
│ 6 │ 1 │ │ │ │
│ 7 │ 5 │ │ │ │
│ 8 │ 3 │ │ │ │
│ 9 │ 2 │ │ │ │
├───────┴───────┴───────┴───────┴───────┤
│ 10 rows 5 columns │
└───────────────────────────────────────┘