2010-09-09 102 views
6

ReporterTbl有一個與AttachmentTbl一對多的關係。如何計算一對多的關係

ReporterTbl,我有一個ID(101),我可以有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 
) 

基本上,我想知道有關AttachmentTbl多個Attachment s的給出ReporterTbl.ID,多少Attachment小號我有嗎?

表結構:

ReporterTbl 

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

    AttachmentTbl: 

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

回答

18
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 
2

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

豈不只是:

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

當然,如果你想要一個記者。 – 2010-09-09 19:20:23

+1

但這就是他要求的.... – 2010-09-09 19:21:18

5

如果你想獲得的所有字段報道(不僅ID),這會爲你節省JOIN

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