I have a model similar to the following:
Alert:
+ id : int
+ timestamp : datetime
+ message : text
UserAlert:
+ id : int
+ user_id : int, foreign key User.id
+ alert_id : int, foreign key Alert.id
+ archive : bool, default false
Basically, I'm creating alerts which are shared by multiple users (which users receive the alerts varies depending on the alert), but each user can "archive" each alert within his own alert inbox.
The problem: How do I give a particular user his newest non-archived alerts in a split second? ... or put more precisely, how do I create an index which runs the following query with optimum efficiency?
SELECT a.id, a.timestamp, a.message
FROM UserAlert AS ua
INNER JOIN Alert AS a
ON a.id = ua.alert_id
WHERE ua.user_id = 1234 and ua.archive = false
ORDER BY a.timestamp DESC
LIMIT 100;
Basically, I need an index on columns (UserAlert.user_id, Alert.timestamp)
. But I don't know how to create an index which uses multiple columns from two or more related tables. Seems like it should be a common problem, but I don't know what words to look for on Google, and so here I am looking for a nudge in the right direction.