如何计算一对多的关系

Nic*_*ahn 8 sql sql-server-2008

ReporterTbl与...有一对多的关系AttachmentTbl.

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
)
Run Code Online (Sandbox Code Playgroud)

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

表结构:

 ReporterTbl

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

    AttachmentTbl:

    AttachmentId indentity
    Id {**FK to ReproterTbl**}
    Filename
    Content
    ...
Run Code Online (Sandbox Code Playgroud)

Red*_*ter 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
Run Code Online (Sandbox Code Playgroud)


Qua*_*noi 7

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

SELECT  r.*,
        (
        SELECT  COUNT(*)
        FROM    AttachmentTbl a
        WHERE   a.id = r.id
        ) AS AttachmentCount
FROM    ReportedTbl r
Run Code Online (Sandbox Code Playgroud)

  • 使用这种方式通常比使用联接更快吗?我之所以这样问,是因为“为你保留一个‘JOIN’”这个措辞 (2认同)