gpt4 book ai didi

sql - 带有 CASE 条件的 Postgresql LEFT JOIN

转载 作者:行者123 更新时间:2023-12-04 02:07:59 27 4
gpt4 key购买 nike

我想在 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;

最佳答案

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

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

关于sql - 带有 CASE 条件的 Postgresql LEFT JOIN,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22461310/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com