在类型为CASE的情况下,从JOINed表中选择列为多个列

时间:2020-05-14 17:57:19

标签: postgresql join

我想通过连接到另一个表中的两行来修饰结果集中的每行的两列。

考虑以下查询:

SELECT
    entity.id,
    entity.created,
    entity.deleted,
    entity.code,
    entity.accountid,
    entity.batchid,

        -- whenever a row from limits matches by ID and has action = 'a'
        -- I'd like to grab the counter value and set it on the column 'limit_a'
    COALESCE(CASE WHEN limits.action = 'a' THEN limits.counter END, 0) AS limit_a,

        -- whenever a row from limits matches by ID and has action = 'b'
        -- I'd like to grab the counter value and set it on the column 'limit_b'
    COALESCE(CASE WHEN limits.action = 'b' THEN limits.counter END, 0) AS limit_b,
FROM
    entity,
    limits
WHERE (entity.deleted IS NULL
    AND entity.accountid = 701
    AND limits.action = 'redeemCoupon'
    AND limits.entityid = entity.id
    AND entity.value = 'aabbaaba');

此查询获取我想要的数据,但它返回两行-limits中的每个匹配行一个。由于我知道limits相对于entityid, action具有UNIQUE约束,因此我希望根据limits.action中的值,将限制中的两行都填充到结果集中的正确列。


我尝试的替代方法是使用WITH条款:

SELECT
    entity.id,
    entity.created,
    entity.deleted,
    entity.code,
    entity.accountid,
    entity.batchid,
    limit_action_a.counter AS limit_a,
    limit_action_b.counter AS limit_b

FROM
    entity,
WHERE (entity.deleted IS NULL
    AND entity.accountid = 701
    AND entity.value = 'aabbaaba')
LEFT JOIN
    limits AS limit_a
ON 
    limit_a.entityid = entity.id
AND
    limit_a.action = 'a'
LEFT JOIN
    limits AS limit_b
ON 
    limit_b.entityid = entity.id
AND
    limit_b.action = 'b'

第二个变体也可以工作,并且为entity的每个结果生成一行,但是我发现第二个查询的性能要差得多,因为查询计划者现在将尝试对entity进行顺序扫描由于某些原因!

更新:为解决此问题,我跟踪了将主查询包装在WITH块中的情况,之后为每行添加了limits中的数据。这是有希望的,直到我意识到不允许我对limit_a.counterlimit_b.counter)的值添加约束。


将多列从另一个表的多行中的单个列添加到结果集中的首选方法是什么?

0 个答案:

没有答案