简体   繁体   中英

MySQL count number of occurrences of field value with join data

I have 2 tables in my database, see below:

Events Table

title | venue_id
event 1 | 1
event 2 | 1
event 3 | 1
event 4 | 1
event 5 | 2
event 6 | 2
event 7 | 2
event 8 | 2
event 9 | 3
event 10 | 3

Venues Table

id | title
1  | Venue 1
2  | Venue 2
3  | Venue 3

The desired results I am looking for would be

venue_title | event_count
Venue 1     | 4
Venue 2     | 4
Venue 3     | 2

I have been trying to do this with joins but for some reason I am getting the count 1 back for every venue.

This is what my SQL looks like just now.

SELECT
  count(DISTINCT events.venue_id),
  venues.title,
FROM
  events
INNER JOIN
  venues
  ON venues.id = events.venue_id

I have looked around various over SO posts but unable to find anything that has been able to help. I am really a beginner at SQL like this.

Thanks

You're missing the group by clause:

SELECT
  count(DISTINCT events.venue_id),
  venues.title,
FROM
  events
INNER JOIN
  venues
  ON venues.id = events.venue_id
GROUP BY -- Here!
  venues.id, venutes.title
  • You can do a group by on events table, get the results and do an inner join of this obtained result with venues table. This can also improve performance of inner join since it will have to map fewer number of rows.

SQL:

select v.title,derived.event_count
from venues v
inner join (select venue_id,count(venue_id) as event_count
from events 
group by venue_id) derived
on v.id = derived.venue_id

you can also use GROUP BY and HAVING clause

SELECT
      count(events.venue_id),venues.title,
    FROM events
    INNER JOIN venues
      ON venues.id = events.venue_id group by events.venue_id having count(events.venue_id) > 0

The GROUP BY Clause is used to group rows with same values and HAVING clause is used to restrict the results returned by the GROUP BY clause.

so > 0 return the duplicate values having count > 0

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