Postgresql LEFT JOIN with CASE condition

时间:2014-03-17 17:34:47

标签: sql left-join case postgis 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;

1 个答案:

答案 0 :(得分:5)

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

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列,其中包含日期或月份列。它将有更多行,但更容易查询。