如何更新max()值-postgresql

ig9co6j1  于 2021-08-13  发布在  Java
关注(0)|答案(1)|浏览(320)

我有两张table:

id  name    group_id    group_name  sub_state
1   User1       1            MG      active
2   User3       3            AG      active

表B

tableA_id       v_date                group_id
   1        2020-01-20T21:51:24.000Z     1          
   2        2020-03-10T21:20:24.000Z     3   
   1        2020-05-05T23:20:24.000Z     1   
   2        2020-05-13T23:20:24.000Z     3

我想更新最新的 v_date 每个用户的新日期。我相信在这里使用max()会很有用。
我试过:

UPDATE tableB
SET v_date = '2020-05-27 20:00:13+00'
WHERE v_date = (SELECT MAX(v_date) FROM tableB
     LEFT JOIN tableA ON tableB.tableA_id = tableA.id AND tableB.group_id = tableA.group_id
     WHERE tableA.sub_state = 'active'
     GROUP BY tableA.id);

此查询返回错误: Query Error: error: more than one row returned by a subquery used as an expression 然后我试着:

WITH stat AS (
    SELECT MAX(v_date) FROM tableB
    LEFT JOIN tableA ON tableB.tableA_id = tableA.id AND tableB.group_id = tableA.group_id
    WHERE tableA.sub_state = 'active' AND tableA.group_id = 1
    GROUP BY tableA.id
)   
UPDATE tableB
SET v_date = '2020-05-27 20:00:13+00'
FROM stat
WHERE group_id = 1;

这会更改所有记录的日期,而不仅仅是最后一个或最近一个记录。
如何更新每个用户的最后一条记录而不影响所有时间的所有记录?

tyg4sfes

tyg4sfes1#

我认为你想要:

UPDATE tableB
SET v_date = '2020-05-27 20:00:13+00'
WHERE v_date = (
    SELECT MAX(tb1.v_date) 
    FROM tableB tb1
    WHERE tb1.tableA_id = tableB.tableA_id
)

相关问题