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;
4

1 回答 1

6

这是一个非常不寻常的查询,我认为它是无效的。即使条件连接是有效的,查询规划器也很难进行优化。可以重写它以加入单个联合表:

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列标准化为conc具有日期或月份列的一列。它将有更多的行,但更容易从中查询。

于 2014-03-17T21:49:32.837 回答