我想在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;发布于 2014-03-18 05:49:33
这是一个非常不寻常的查询,我不认为它是有效的。即使条件连接是有效的,查询规划器也很难进行优化。可以将其重写为连接到单个联合表:
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)组织io_postcode_ratios表的一种更好的方法(如果可以这样做的话)可能是将每月的*_conc列规范化为一个包含date或month列的conc列。它将有更多的行,但更容易查询。
https://stackoverflow.com/questions/22461310
复制相似问题