Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to count one to many relationships

ReporterTbl has a one to many relationship with AttachmentTbl.

In ReporterTbl, I have an ID (101) and I can have AttachmentTbl more than one Attachments related with 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
)

Basically, what I am trying to know is given ReporterTbl.ID, how many Attachments do I have?

Table structure:

 ReporterTbl

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

    AttachmentTbl:

    AttachmentId indentity
    Id {**FK to ReproterTbl**}
    Filename
    Content
    ...
like image 633
Nick Kahn Avatar asked Sep 09 '10 19:09

Nick Kahn


People also ask

How do you count in SQL?

In SQL, you can make a database query and use the COUNT function to get the number of rows for a particular group in the table. Here is the basic syntax: SELECT COUNT(column_name) FROM table_name; COUNT(column_name) will not include NULL values as part of the count.


3 Answers

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
like image 133
D'Arcy Rittich Avatar answered Sep 27 '22 04:09

D'Arcy Rittich


If you want to get all fields from Reported (not only ID), this will save you a JOIN:

SELECT  r.*,
        (
        SELECT  COUNT(*)
        FROM    AttachmentTbl a
        WHERE   a.id = r.id
        ) AS AttachmentCount
FROM    ReportedTbl r
like image 38
Quassnoi Avatar answered Sep 29 '22 04:09

Quassnoi


given ReporterTbl.ID how many attachments i have.

Wouldn't it just be:

select count(*) from AttachmentTbl where id = @ID;
like image 33
James Curran Avatar answered Oct 01 '22 04:10

James Curran