The database has several tables:
- Tours
- Bookings
- Guides
Now every tour can have n bookings and every guide can have n tours. However, on my homepage I only want to show a list of 5 tours with a limit of 1 tour per guide. However, if I take the bookings from a left join, I need to group by "tourId", but on the other side I also need to group by "tourGuideId" to have a limit of 1. If I GROUP BY tourGuideId it shows me only one tour per guide, but makes problems with the LEFT JOIN and shows bookings although there aren't. If I GROUP BY tourId it works with the LEFT JOIN but not with the limit of 1 per guide.
Here is the simple query:
SELECT f.*, SUM(b.bookingSeats) AS bookings
FROM tours AS f
LEFT JOIN bookings AS b ON f.tourId = b.bookingTourId
WHERE f.tourActive = '1'
GROUP BY f.tourGuideId
ORDER BY f.tourId DESC
LIMIT 5
How to proceed?
Edit 1: a simple "GROUP BY f.tourGuideId, f.tourId" doesn't work. It makes the LEFT JOIN work but doesn't limit to 1 result per guide.
Edit 2: Sample result should be:
tourId, tourGuideId, tourTitle, tourDate, tourActive, bookings
5, 1, 'Hello World', '2016-12-01 08:00:00', 1, NULL
9, 3, 'Tour Paris', '2017-03-01 08:00:00', 1, 3
Bookings Table structure:
bookingId, bookingStatus, bookingUserId, bookingDate, bookingPaid
Tour Table structure:
tourId, tourGuideId, tourTitle, tourDate, tourActive