【问题标题】:how to use update query in to update query in postgresql如何在 postgresql 中使用更新查询来更新查询
【发布时间】:2021-11-12 17:32:36
【问题描述】:

我想更新 ChannelInfo 报告 ChannelId 更新行返回的内容 但是这个查询不工作,报错:

ERROR:  syntax error at or near ""AdsReporting""
LINE : where "CampaignInfo"."id" in (update "AdsReporting" set "adS...
                                             ^
SQL state: 42601
Character: 240 

谁能帮帮我?

上报ChannelId是与ChannelInfo主键的外键关系。

代码:

update "ChannelInfo" set "Amount"=CASE WHEN "Duration"='60' THEN "Amount"-12.25 ELSE "Amount"-6.13 END 
where "id"=(update "Reporting" set "Status"='run' where "Status"='a' RETURNING "ChannelId");

【问题讨论】:

  • 请提供示例数据、期望的结果以及您要实现的逻辑的清晰说明。
  • 此查询工作正常,但 channelInfo 和 Reporting 具有一对多关系,因此(从 u 中选择 u.ChannelId)可以返回相同的两个广告系列 id,因此它有两个减去 Amount 2 倍,但它只有减去一个时间。
  • 示例这是选择查询返回,u 为(更新“报告”设置“状态”=“运行”,其中“状态”=“a”返回“频道 ID”)更新“频道信息”设置“金额"= (CASE WHEN "Duration" = '60' THEN "Amount" - 12.25 ELSE "Amount" - 6.13 END) where "id" in (3, 3);它必须减去 ChannelInfo Amount 两次,但它只减去 Amount 一次
  • 您好,您能帮帮我吗?
  • 你好@GordonLinoff

标签: sql database postgresql sql-update


【解决方案1】:

听起来你想使用 CTE:

with u as (
      update "Reporting"
          set "Status" = 'run'
          where "Status" = 'a'
      RETURNING "ChannelId"
     )
update "ChannelInfo" ci
    set "Amount"= (CASE WHEN ci."Duration" = '60' THEN ci."Amount" - uc.cnt * 12.25 ELSE ci."Amount" - uc.cnt * 6.13 END)
    from (select "ChannelId", count(*) as cnt
          from users u
          group by "ChannelId"
         ) uc
    where uc."ChannelId" = ci.id;

【讨论】:

  • where "id" in (select u.ChannelId from u) - 如果 Reporting 表返回两个相同的 ChannelId,那么它会运行并减去 Amount 一次,因为 ChannelInfo 和 Reporting 关系是一对多的,所以我要做什么,如果它返回 ChannelId 2 次,它将减去 2 次。
  • @UmAiRShAhiD 。 . .这真的很奇怪。答案中的查询不是我写的。也许我在保存答案时不小心删除了实际查询。
猜你喜欢
  • 2015-10-28
  • 1970-01-01
  • 2021-12-20
  • 2021-07-10
  • 2021-01-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多