I have some pretty complex queries that I have to run on a large database table containing events. I have several tables but these questions relate to 3 or 4 of them. :bemused:
events - the big table full of events
id
name
start_time
end_time
other fields...
subcategories - each event fits up to five of these 50 different subcats
id
name
cat_id - connects to the categories table id field
categories - each subcategory fits in one of these 10 or so cats
id
name
event_subcat_assoc
id
event_id - connects to the events table id field
subcat_id - connects to the subcategories table id field
I have two questions.
1) My first query problem is that I have is that I am supposed to design my page to select 3 events at random from each category. Given the size of my database and the complexity of my query, I am trying to use ORDER BY RAND() to retrieve these random events in the hope that it will be faster.
But this seems to require that I run what is essentially the same query once for each category.
$cat_id = 1; // id 1 is category 'music'
// this might be more efficient as SELECT DISTINCT...
$sql = "SELECT e.id, e.name, e.start_time COUNT(esa.id) FROM events e, subcategories s, categories c, event_subcat_assoc esa WHERE esa.event_d=e.id AND esa.subcat_id=s.id AND s.cat_id=$cat_id GROUP BY e.id ORDER BY RAND()";
QUESTION: Can anyone recommend a way to get 3 random events for each category with only one query rather than running this query over for each category?
2) The page is also supposed to display all the subcategories associated with any given event which need not all belong to the same category. Once I have retrieved my random events, I must run another query to grab the subcategory names for each event.
QUESTION: Can I somehow grab all the subcategory names when I grab the event in the first place? There are fifty subcategories and I just can't think of any way to summarize 5 records from the event_subcat_assoc (and their name from the subcats table) as a single record in my primary random events query.