The*_*ady 1 sql postgis case left-join postgresql-9.3
我想在PostgreSQL中使用CASE条件来决定要加入的另一个表的哪一列.这就是我所在的地方,我认为,这解释了我正在努力做的事情.非常感谢您的想法和想法:
SELECT hybrid_location.*,
concentration
FROM hybrid_location
CASE WHEN EXTRACT(month FROM hybrid_location.point_time) = 1
THEN LEFT JOIN (SELECT jan_conc FROM io_postcode_ratios) ON
st_within(hybrid_location.the_geom, io_postcode_ratios.the_geom) = true
WHEN EXTRACT(month FROM hybrid_location.point_time) = 2
THEN LEFT JOIN (SELECT feb_conc FROM io_postcode_ratios) ON
st_within(hybrid_location.the_geom, io_postcode_ratios.the_geom) = true
ELSE LEFT JOIN (SELECT march_conc FROM io_postcode_ratios) ON
st_within(hybrid_location.the_geom, io_postcode_ratios.the_geom) = true
END AS concentration;
Run Code Online (Sandbox Code Playgroud)
这是一个我认为无效的非常不寻常的查询.即使条件连接有效,查询规划器也很难进行优化.可以重写它以加入单个联合表:
SELECT hybrid_location.*,
concentration
FROM hybrid_location
LEFT JOIN (
SELECT 1 AS month_num, jan_conc AS concentration, io_postcode_ratios.the_geom
FROM io_postcode_ratios
UNION ALL
SELECT 2 AS month_num, feb_conc AS concentration, io_postcode_ratios.the_geom
FROM io_postcode_ratios
UNION ALL
SELECT 3 AS month_num, march_conc AS concentration, io_postcode_ratios.the_geom
FROM io_postcode_ratios
) AS io_postcode_ratios ON
EXTRACT(month FROM hybrid_location.point_time) = io_postcode_ratios.month_num
AND ST_Within(hybrid_location.the_geom, io_postcode_ratios.the_geom)
Run Code Online (Sandbox Code Playgroud)
可能更好的组织io_postcode_ratios表格的方法(如果这是一个选项)是将每月*_conc列标准化为一conc列,其中包含日期或月份列.它将有更多行,但更容易查询.