sql - 根据另一个表中的条目数在一个表中设置一个值
问题描述
所以我对使用数据库相当陌生,所以如果这是一个明显的问题,我提前道歉。我有以下问题。在我的数据库中,我有两个带有条目的表。在表 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.
解决方案
您可以使用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);
推荐阅读
- kubernetes - 在 Kubernetes 中调整持久卷的大小时出错
- php - 如何使最后一个数组键的数据移动到第一个数组键?倒数第二个数组键的数据移动到第二个数组键
- sql - 我怎样才能获得大于或等于 sql 或 laravel eloquent 中的人的记录
- eclipse - 从 ECLIPSE IDE 导出 Word 文档
- android - 如何在 Android Studio 运行时以编程方式设置构建变体?
- javascript - 如何使用 JavaScript 检测 JSP 是否加载到 PORTLET 或浏览器中?
- python - 按月份和这些月份的小时数对 pandas 数据框进行分组
- linux - 从bash中的给定日期减去月份
- database-design - 如何将富文本编辑器的状态存储在泛化到 Web 和移动应用程序的数据库中?
- laravel - Laravel 黄昏无法输入完整的输入