0

当前查询是:

update topics set posts = (select count(*) from posts where tid = 27), lastpost = (select max(pid) from posts where tid = 27) where tid = 27;

如何将两个子查询合并到更新查询中?

select count(*), select max(pid) from posts where tid = 27)

显然,我可以将其作为两个单独的查询来执行(从帖子中读取值,将值写入主题),但如果可能的话,我想在单个查询中执行此操作。

4

1 回答 1

0

您可以inner join在更新语句中使用 an :

update topics t
  join (
        select tid, count(*) as cnt, max(pid) as mx
          from posts
         group by tid
       ) p on p.tid = t.tid 
   set posts = p.cnt, lastpost = p.mx
 where t.tid = 27;

Demo

附带说明: 在这种情况下不需要,但从 DB 版本 10.2 开始,窗口分析函数也可以与聚合函数一起使用。

于 2020-01-12T11:59:53.447 回答