我有两张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;
这会更改所有记录的日期,而不仅仅是最后一个或最近一个记录。
如何更新每个用户的最后一条记录而不影响所有时间的所有记录?
1条答案
按热度按时间tyg4sfes1#
我认为你想要: