Count rows of a table related to a query

I have two tables. (In reality there are more than that, but for the sake of this question, let's say there are two).

Table 1: Contacts
Tabe 2: projects.

Projects is related to contacts in that `projects`.`ownerId` is an integer value that matches `contacts`.`contactId`.

The relatinoship is a one to many. (One contact can have multiple projects).

I want to get a project count for each contact.

So, SELECT * FROM contacts would be the base query. But I want a row for each contact that counts the number of projects they have from the projects table.

The ideal output would be:

Firestname | LastName | Email                                 | Projects
Jim              | Smith        | jim.smith@example.com | 25

Open in new window


What's the SQL query to do this?
LVL 32
DrDamnitAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

AshokSr. Software EngineerCommented:
Try

select c.Firstname, c.LastName, c.Email, Count(c.contactId) As Projects
from Contacts c, Projects p
where c.contactId = p.ownerId
group by c.contactId
0
mbizupCommented:
Try something like this:

SELECT c.FirstName, c.Lastname, c.Email, Count(p.ProjectID) AS ProjectCount
FROM contacts c LEFT JOIN projects p on c.contactId = p.ownerID
GROUP BY c.FirstName, c.Lastname, c.Email

Open in new window

0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
AshokSr. Software EngineerCommented:
Try

select c.Firstname, c.LastName, c.Email, Count(c.contactId) As Projects
from Contacts c, Projects p
where c.contactId = p.ownerId
group by c.Firstname, c.LastName, c.Email
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
MySQL Server

From novice to tech pro — start learning today.