Skip to content
Advertisement

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

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

Table structure:

Advertisement

Answer

Note: It is important that we are using count(a.id), and not count(*). This is because count will ignore null values when we count the results of an expression. If instead we use count(*), SQL will count the resulting rows, so any rows from ReporterTbl that don’t have a matching row in AttachmentTbl would return a count of 1 because we still return the row due to the left join.

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement