简体   繁体   中英

How do I get count of duplicated values and join the table to retrieve each value's name?

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?

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.

SELECT venues.venue_name, COUNT(volunteers.*) AS cvolun
  FROM venues
  INNER JOIN volunteers
    ON venues.id = volunteers.venue_id

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM