2010-09-09 40 views
6

ReporterTbl có mối quan hệ một đến nhiều với AttachmentTbl.Cách tính một đến nhiều mối quan hệ

Trong ReporterTbl, tôi có một ID (101) và tôi có thể có AttachmentTbl nhiều hơn một Attachment s liên quan với 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 
) 

Về cơ bản, những gì tôi đang cố gắng để biết được đưa ra ReporterTbl.ID, có bao nhiêu Attachment s tôi có

Bảng cấu trúc:

ReporterTbl 

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

    AttachmentTbl: 

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

Trả lời

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

cho ReporterTbl.ID bao nhiêu file đính kèm tôi có.

Nó sẽ không chỉ là:

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

Chắc chắn, nếu bạn muốn một phóng viên tại một thời điểm. –

+1

Nhưng đó là những gì anh ta yêu cầu .... –

5

Nếu bạn muốn để có được tất cả các lĩnh vực từ báo cáo (không chỉ ID), điều này sẽ giúp bạn tiết kiệm JOIN:

SELECT r.*, 
     (
     SELECT COUNT(*) 
     FROM AttachmentTbl a 
     WHERE a.id = r.id 
     ) AS AttachmentCount 
FROM ReportedTbl r 
Các vấn đề liên quan