I’m attempting to condense several SQL calls into one, and wanted to know if the following were possible.
Here are are my tables.
Organization
id
Event
id,
startDate
endDate
FavoriteOrgs
userId
orgId
For each day of the month, I want to return a count of the events occurring on that day. Not too difficult, until you add the fact that events can span 2 or 3 days.
Here’s what I have so far, which accurately shows event counts by day, but it only includes the event in count for the day it begins.
SELECT DAYOFMONTH( CAST( o.start_date AS DATE ) ) AS dayNum, COUNT( * ) AS count
FROM favoriteOrgs f, event e, organization o
WHERE f.user_id =200372
AND e.profile_id = o.id AND e.profile_id = f.profile_id AND o.id = f.profile_id
AND e.last_date >= '$startDate'
AND e.start_date <= '$lastDate'
GROUP BY e.start_date
Your data model isn’t actually modeling all of the entities in your system. One entity is the dates for which you are interested in reporting things.
You should add a table to your database (or use a temporary table, inline table, or whatever else is available with MySQL). The table is simply all of the relevant dates. Even a table that goes back to 1900 and forward to 2100 is going to be fairly small.
The query then becomes trivial:
You also now have an advantage that you can add additional business specific information to calendar dates, like an “is_holiday” column, “economic_quarter” or whatever. Just remember to prefill the table, which is a simple loop that you have to run once.