简体   繁体   中英

Query design, temporary table? MySQL

I have two tables, users and events, and I want to select eg 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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM