Reputation: 24019
I have two tables, users and events, and I want to select e.g. 6 users from the USERS table and list all of their events in chronological order of the event date
table design:
USERS EVENTS
user_id >>>> user_id
event_title
event_date
Do I select all the events into a temporary table then query that with "order by" or is there a more efficient way to do this within the query itself?
Upvotes: 1
Views: 171
Reputation: 839234
This will select six arbitrary users from your users table and fetch all their events:
SELECT user_id, event_title, event_date
FROM EVENTS
WHERE user_id IN
(
SELECT user_id
FROM USERS
LIMIT 6
)
ORDER BY event_date
You should change the subselect to select six specific users based on your desired criteria, instead of just the first six that MySQL finds.
You should add indexes to ensure that this runs efficiently. Use EXPLAIN SELECT ...
to check which indexes are being used.
Upvotes: 1