如何从数据库中选择重叠的值对
在我的 postgres 数据库中,我有一个包含 3 列的表,如下所示:
start | end | sorce
17 | 23 | A
150 | 188 | A
200 | 260 | A
19 | 30 | B
105 | 149 | B
199 | 220 | B
...
我想选择来自不同源 A 和 B 的区域(从开始到结束)重叠的所有行。
更新:
从 postgres 8.4 版开始,可以使用 窗口函数。它比连接或子选择方法快得多。 链接到 postgres wiki。
In my postgres db I have a table with 3 columns like this:
start | end | sorce
17 | 23 | A
150 | 188 | A
200 | 260 | A
19 | 30 | B
105 | 149 | B
199 | 220 | B
...
I would like select all row where the regions (start to end) from the differed sources A and B are overlapping.
UPDATE:
From postgres version 8.4 it is posible to solve the problem with window functions. It is much more faster than the join or subselect methodes. Link to postgres wiki.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这是一种强力方法(我将您的列 range_start 和 range_end 重命名,以避免与保留字“end”冲突):
或者
您应该能够使用 GiST 索引,这可能会提高效率(seq scan +索引扫描):
此函数可以通过清理 SQL 来帮助理解:
使用此函数,您可以编写:
并注意
框 && box
运算符表示“重叠”。This works as a brute-force approach (I renamed your columns range_start and range_end to avoid conflict with the reserved word "end"):
or
You should then be able to use a GiST index which may make this a more efficient (seq scan + index scan):
This function might aid understanding by clearing up the SQL:
With this, you can write:
and note that the
box && box
operator means "overlaps".如果您想要所有配对,则使用经典重叠测试 INNER JOIN A 和 B
,即,
如果您不是指源
字面上
'A'和'B',只是它们不同,您可以使用根据您对重叠的定义,将
<
与<=
交换(两次)<
: 10-20 会 < em>不重叠 20-30<=
: 10-20 确实重叠 20-30If you want all pairings, then INNER JOIN A and B using the classic overlap test
i.e
If you do not mean sources
literally
'A' and 'B', just that they are different, you can use the below insteadDepending on your definition of overlapping, swap the
<
with<=
(both times)<
: 10-20 does not overlap 20-30<=
: 10-20 does overlap 20-30