I have a mysql database with two tables, bookings and users.
They are linked via a foreign key user_id in the bookings table.
How would I go about showing the number of bookings per user.
I’ve been trying variations on this query:
select first_name, last_name, count(*)
from bookings
left join users on bookings.user_id
group by user_id
order by count(*);
But it’s locking the database for an incredibly long time.
First, your ON clause is not complete. Usually it will be
ON X=Y, you haveON X. THis is important because you are telling the database how to link your two tables. I’m guessing this is where the most time is lost.Second, the LEFT JOIN as used here is useless (unless you want the bookings that have no users.) Try an INNER JOIN.
Third, as a general rule, it’s better to do
SmallTable INNER JOIN BigTable(not always, your mileage may vary.)Fourth, as mentioned, use an alias for the ORDER BY clause.
Try: