I’m tring to write a query, without a good resultset.
I would to retreive a Number of reservations in last 7 days.
Grouped by NameOfResource.
When i’m tring to set a WHERE clause like this prenotazioni.Data >= CURDATE() - INTERVAL 7 DAY
I get only NameOfResource with reservations in latest 7 days,
but not the rooms without reservations.
My Query was like that: (without WHERE the result is good)
SELECT count(*) as NReservationsFromWeek,Nomeroom FROM reservations INNER JOIN room ON reservations.FKRoom = room.IDRoom WHERE reservations.Data >= CURDATE() - INTERVAL 7 DAY group by room.IDRoom
Thank you to explain me where I was wrong.
Advertisement
Answer
You can use a LEFT JOIN
, if you want all rooms, even those with a count of 0
:
SELECT ro.IDRoom, ro.Nomeroom, COUNT(re.FKRoom) as NReservationsFromWeek, FROM room ro LEFT JOIN reservations re ON re.FKRoom = ro.IDRoom AND re.Data >= CURDATE() - INTERVAL 7 DAY GROUP BY ro.IDRoom, ro.Nomeroom; -- Both unaggregated keys should be in the GROUP BY