微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

sql – 如何计算一对多关系

ReporterTbl与AttachmentTbl有一对多的关系.

在ReporterTbl中,我有一个ID(101),我可以使用AttachmentTbl多个与ReporterTbl.Id相关的附件

SELECT     
ISNULL(ReporterTbl.Id,0) AS Id,CONVERT(char(10),ReporterTbl.StartDate,101) AS StartDate,ISNULL(ReporterTbl.PriorityId,0) AS PriorityId,ISNULL(dbo.ReporterTbl.PriorityDesc,'') AS PriorityDesc,(select       
   ReporterTbl.Id,COUNT(dbo.AttachmentTbl.Id) AS attachment_Id
FROM         
dbo.AttachmentTbl RIGHT OUTER JOIN
ReporterTbl ON dbo.AttachmentTbl.Id = ReporterTbl.Id
GROUP BY ReporterTbl.Id) AS IsAttachment
)

基本上,我想知道的是ReporterTbl.ID,我有多少个附件?

表结构:

ReporterTbl

    Id int   {**PrimaryKey**}
    StartDate datetime
    PriorityId int
    PriorityDesc varchar(500

    AttachmentTbl:

    AttachmentId indentity
    Id {**FK to ReproterTbl**}
    Filename
    Content
    ...

解决方法

select r.id,count(a.id) as Count
from ReporterTbl r
left outer join AttachmentTbl a on r.id = a.id
group by r.id

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐