【问题标题】:How can I port this mongo query to postgres?如何将此 mongo 查询移植到 postgres?
【发布时间】:2013-12-07 13:46:19
【问题描述】:

我有一个原子更新,它通过属性中的最小值查找记录,增加该值,并在一个查询中返回结果。

如果我在 SQL Server 中,我会在事务中使用 DECLARE 和 SET 并执行多个查询,但是这种 postgres DO 语法对我来说是煎饼。

我看到DO $$DECLARE r record; 是一个好的开始,但我可以 SET 或通过其他方式为该变量分配一条记录吗?

在 Mongo 中:

this.findOneAndUpdate(
    { active: true },
    { $inc: { userCount: 1 } },
    { sort: { userCount: 1 } }, // grab the lowest count for update
    cb
);

在 SQL Server 中,我会做这样的事情:(已经有一段时间了……)

declare @id int
begin
    set @id = select top 1 id 
        from foos 
        where active = 1 
        order by userCount desc

    update foos 
        set userCount = userCount + 1 
        where id = @id

    select foos 
        where id = @id
end

【问题讨论】:

    标签: sql mongodb postgresql


    【解决方案1】:

    不需要 do 语句...使用带有返回子句的普通更新语句,例如:

    update foos 
    set userCount = userCount + 1 
    where id = (
          select id 
          from foos 
          where active = 1 
          order by userCount desc
          limit 1
        )
    returning *
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-08-23
      • 1970-01-01
      • 2013-01-18
      • 2012-08-28
      • 1970-01-01
      相关资源
      最近更新 更多