我将SQL Server 2014用于我的项目。我有两个表(主关系和明细关系),如下所示:
Master:
id
detail_count (the number of associated Detail records)
Detail:
id
master_id
detail_count
列是主记录具有的明细记录数。我可以找到每个主记录的计数,如下所示:
select m.id, count(*) from Master m
join Detail d on d.master_id = m.id
group by m.id
我还可以为Master表编写更新语句:
update Master set detail_count = ?
如何结合以上两个语句来更新所有主记录的detail_count
答案 0 :(得分:1)
您可以使用以下查询简单地更新计数:
update Master
set detail_count = (select count(*) from detail where detail.master_id = Master.id)