tags:

views:

214

answers:

2

I have two tables, one that contains volunteers, and one that contains venues. Volunteers are assigned one venue each.

The id of the venues table (venues.id) is placed within the volunteers table in the venue_id column (volunteers.venue_id).

I know I could get a count of how many matching values are in the volunteers.venue_id column by

SELECT venue_id, COUNT(*) FROM volunteers GROUP BY venue_id

Why I want to do this: so the user can go in and see how many volunteers are assigned to each venue.

table: volunteers -- columns: id, name, venue_id

table: venues -- columns: id, venue_name

volunteers.venue_id = venues.id

I know this would be a join statement of some sort so it will get a count of each venue, then match up volunteers.venue_id to venues.id and print out the venues.venue_name along with the count.

How would I go about joining the two tables to print out the venue name and next to it, list the count of each volunteer with that venue_id?

+1  A: 
SELECT venues.venue_name, COUNT(volunteers.*) AS cvolun
  FROM venues
  INNER JOIN volunteers
    ON venues.id = volunteers.venue_id
Ignacio Vazquez-Abrams
An inner join means that it only reports venues that have at least one volunteer. It fails to report any venues that have zero volunteers. That's why an outer join is needed for this problem.
Bill Karwin
+4  A: 

This will give you all of the venues, with those having no volunteers showing up with a 0 volunteer_count

select venues.venue_name, count(*) as volunteer_count
from venues
left outer join volunteers
   on venues.id = volunteers.venue_id
group by venues.venue_name

[EDIT] I just realized you asked for MySQL. I can't remember if MySQL uses LEFT JOIN or LEFT OUTER JOIN. The syntax above would be correct for SQLSERVER. The key point is the outer join instead of the inner join to get the venues that have no volunteers.

tvanfosson
FWIW, both LEFT JOIN and LEFT OUTER JOIN work in MySQL, and they both work in an identical way.
Bill Karwin