首页 > 解决方案 > 根据另一个表中的条目数在一个表中设置一个值

问题描述

所以我对使用数据库相当陌生,所以如果这是一个明显的问题,我提前道歉。我有以下问题。在我的数据库中,我有两个带有条目的表。在表 1 中,所有条目都有一个 ID 和一个包含计数器的字段。在表 2 中,有一个条目具有表 1 中的 ID 作为外键 (fk_table1_id)。我的目标是将 table1 中每个条目的计数器设置为 table2 中具有 table1 条目的 fk_table_id 的条目数。所以基本上我想到了这样的东西(伪代码)

foreach (entries of table1 as entry$entry) {
  update `table1` where `id` = `entry->id` set `count`= {
    count `table2`wehere `fk_table1_id` = entry->id
    }
}

thanks in advance.

标签: sqlmariadb

解决方案


您可以使用join聚合子查询:

update table1 t1 join
       (select fk_table1_id, count(*) as cnt
        from table2 t2
        group by fk_table1_id
       ) t2
       on t2.fk_table1_id = t1.id
    set t1.count = t2.cnt;

注意:这仅设置第二个表中存在行的计数。如果你想要0计数,那么:

update table1 t1 left join
       (select fk_table1_id, count(*) as cnt
        from table2 t2
        group by fk_table1_id
       ) t2
       on t2.fk_table1_id = t1.id
    set t1.count = coalesce(t2.cnt, 0);

推荐阅读