I have a database with two tables, events and tickets. The events table contains rows of events, and tickets each ticket sold.
For example,
events
------
id name capacity
1 Test 10
2 Test2 20
3 Test3 15
tickets
-------
id event_id customer_id
1 1 (value here doesn't matter)
2 1
3 3
4 1
5 3
So I can see that 3 tickets to event #1 have been sold, 0 tickets to event #2, and 2 tickets to event #3 have been sold.
I’m trying to create a query that selects all the events, plus a column available which is the events capacity less the count of tickets sold.
I have this query:
SELECT
events.id,
events.name,
events.capacity,
events.capacity - COUNT(tickets.id) AS available
FROM
events
INNER JOIN tickets ON events.id = tickets.event_id
However, this doesn’t return any events where tickets havn’t yet been sold. I thought it might be the type of join, but I tried various ones with no success.
I’m not sure where I’m going wrong.
You’re almost there, just change the
inner jointo aleft join:Even though MySQL does not require it, it’s good practice to list all non-aggregated columns explicitly in the
group byclause.