0

I have a two tables, one which contains details of events (name,time,etc), and one which contains records of bookings customers have made for each of these events. I want to be able to query the database and get a set of results that contains all the fields in the events table, plus the number of bookings that there have been for each of these events, so something like:

event_name, event_time, total_spaces_available, number_of_bookings

At the moment I'm getting around this by looping through the results in PHP but is it possible to do within SQL?

I want to be able to do something like:

SELECT *, COUNT(SELECT * FROM bookings WHERE event_id=<VARIABLE>) FROM events 

But i don't know the syntax

I'm in MySQL

Any help would be much appreciated!

2 Answers 2

3

Possible solution with a correlated subquery:

SELECT e.event_name, e.event_time, e.total_spaces_available, (SELECT count(*) FROM bookings b WHERE b.event_id=e.event_id) AS number_of_bookings FROM events e 

Edit: Like mentioned in the comments, this may be less performant than the join solution. Although I believe the latest MySQL converts them to joins anyway.

Sign up to request clarification or add additional context in comments.

3 Comments

This is a bad practice because if you have 1000 events, mysql will probably do 1000 subqueries to the bookings, one for each event. There is no guarantee that the optimization will work and rewrite this to be efficient. Subqueries are not advisable.
@saamorim . . . A correlated subquery may be the most efficient way of executing this query, especially when there is an index on bookings(event_id). If you have performance comparisons that suggest otherwise, I would be interested in hearing about it.
This should be fine - check the plans.
1

Do a group by

Select event_name, event_time, total_spaces_available, count(1) number_of_bookings from events inner join booking on events.id = bookings.event_id group by event_name, event_time, total_spaces_available 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.