如何计算一对多的关系

时间:2010-09-09 19:12:43

标签: sql sql-server-2008

ReporterTblAttachmentTbl有一对多的关系。

ReporterTbl中,我有一个ID(101),我可以AttachmentTbl多个与Attachment相关的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,我有多少Attachment

表格结构:

 ReporterTbl

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

    AttachmentTbl:

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

3 个答案:

答案 0 :(得分:22)

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

答案 1 :(得分:6)

如果您想从报告中获取所有字段(不仅仅是ID),这样可以为您节省JOIN

SELECT  r.*,
        (
        SELECT  COUNT(*)
        FROM    AttachmentTbl a
        WHERE   a.id = r.id
        ) AS AttachmentCount
FROM    ReportedTbl r

答案 2 :(得分:2)

  
    

给出ReporterTbl.ID我有多少附件。

  

不会只是:

select count(*) from AttachmentTbl where id = @ID;