【发布时间】:2016-06-07 19:22:28
【问题描述】:
我在 postgreSQL 9.5 数据库中有三个表:
big_table:
- geom_location
a:
- geom_location
- name
b:
- geom_location
- name
geom_location 字段是已编入索引的 postGIS 字段。 a 和 b 表大约有 200K 行,而 big_table 大约有 20M 行。
我需要创建一个产生以下结果的选择语句:
- a_name - 如果在表 a 的 geom_location 2Km 内有一个 big_table 条目,这将是它的关联名称。否则,它将为空。
- b_name - 如果在表 b 的 geom_location 2Km 内有一个 big_table 条目,这将是它的关联名称。否则,它将为空。
- geom_location - 距离表 a、b 或两者中的条目 2 公里范围内的 geom_location。
- 我不想取回任何 a_name 和 b_name 都为空的行。
以下接近我想要的,但它要求所有三个 geom_locations 都在 2Km 内:
SELECT t.geom_location, a.name as a_name, b.name as b_name
FROM big_table t
INNER JOIN a ON ST_DWithin(t.geom_location, a.geom_location, 2000)
INNER JOIN b ON ST_DWithin(t.geom_location, b.geom_location, 2000)
这也非常接近,但它并没有按照我想要的方式组合行:
SELECT t.geom_location, a.name as a_name, null as b_name
FROM big_table t
INNER JOIN a ON ST_DWithin(t.geom_location, a.geom_location, 2000)
UNION
SELECT t.geom_location, null as a_name, b.name as b_name
FROM big_table t
INNER JOIN b ON ST_DWithin(t.geom_location, b.geom_location, 2000)
似乎应该有某种语法来执行“大部分”内连接——也就是说,两个表相对于第一个表将内连接设为内连接,但相对于第一个表进行完全连接彼此。
【问题讨论】:
标签: sql inner-join postgis