2010-09-09 4 views
6

ReporterTbl имеет отношение «один ко многим» с AttachmentTbl.Как посчитать один ко многим отношениям

В ReporterTbl, у меня есть удостоверение личности (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 
    ... 

ответ

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

Конечно, если вам нужен один репортер одновременно. –

+1

Но это было то, о чем он просил .... –

5

Если вы хотите, чтобы получить все поля из Сообщил (а не только ID), это сэкономит вам JOIN:

SELECT r.*, 
     (
     SELECT COUNT(*) 
     FROM AttachmentTbl a 
     WHERE a.id = r.id 
     ) AS AttachmentCount 
FROM ReportedTbl r 
Смежные вопросы