By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
429,101 Members | 1,340 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 429,101 IT Pros & Developers. It's quick & easy.

SQL count across two tables in a one to many relationship

P: n/a
Hello!

I have two tables, USERS and PHOTOS, in a one to many relationship like this...

USERS:
UserID: Name:
1 Bob
2 Frank
3 Jim
4 Bill
5 Keith

PHOTOS:
PhotoID: ImagePath: OwningUserID:
A test.jpg 1
B test2.jpg 1
C test3.jpg 2
D test4.jpg 2
E test5.jpg 3

So, here we see:
- Bob has 2 photos, test.jpg and test2.jpg
- Frank has 2 photos, test3.jpg and test4.jpg
- Jim has one photo, test5.jpg
- Bill and Keith have no photos

What I need is an SQL query that returns this recordset:

QUERYRESULT:
Name: NumberOfPhotos:
Bob 2
Frank 2
Jim 1
Bill 0
Keith 0

Can anybody help?

Thanks,

Al
Nov 13 '05 #1
Share this Question
Share on Google+
2 Replies


P: n/a
Try this, Al, and let me know how it goes:

SELECT USERS.Name, Count(PHOTOS.PhotoID) AS NumberOfPhotos
FROM USERS LEFT JOIN PHOTOS ON USERS.UserID = PHOTOS.OwningUserID
GROUP BY USERS.Name
ORDER BY Count(PHOTOS.PhotoID) DESC;

------------
LoopyNZ
------------

*** Sent via Developersdex http://www.developersdex.com ***
Don't just participate in USENET...get rewarded for it!
Nov 13 '05 #2

P: n/a
Hello!

Perfect. Thank you very much.

Al
Try this, Al, and let me know how it goes:

SELECT USERS.Name, Count(PHOTOS.PhotoID) AS NumberOfPhotos
FROM USERS LEFT JOIN PHOTOS ON USERS.UserID = PHOTOS.OwningUserID
GROUP BY USERS.Name
ORDER BY Count(PHOTOS.PhotoID) DESC;

Nov 13 '05 #3

This discussion thread is closed

Replies have been disabled for this discussion.