简体   繁体   中英

MySQL subquery with LIMIT alternative

What I want:

SELECT u.username, u.last_activity 
FROM users_userprofile 
WHERE u.id IN (
    SELECT DISTINCT(p.user_id) FROM forums_post p 
    WHERE p.thread_id = 423993 
    ORDER BY p.created_at DESC 
    LIMIT 4
);

This doesn't work because of LIMIT in subquery. I want to keep order of subquery but I want to get username and last_activity instead of user_id .

Any suggestion how I could achieve this?

Replace the subquery with a view:

CREATE VIEW subv AS     SELECT p.user_id FROM forums_post p 
WHERE p.thread_id = 423993 
ORDER BY p.created_at DESC 
LIMIT 4;

SELECT u.username, u.last_activity 
FROM users_userprofile 
WHERE u.id IN (SELECT * FROM subv);

Why woldn't you do it with a JOIN ? There seems to be no performance impact because WHERE and LIMIT clauses are the same. It won't JOIN the whole tables:

SELECT p.user_id, u.username, u.last_activity 
FROM users_userprofile u
JOIN forums_post p ON p.user_id = u.id
WHERE p.thread_id = 423993 
GROUP BY p.user_id ORDER BY MAX(p.created_at) DESC 
LIMIT 4

you could use join for the table and the subquery instead of using where in :

SELECT u.username, u.last_activity 
FROM users_userprofile u
JOIN (
       SELECT p.user_id FROM forums_post p 
       WHERE p.thread_id = 423993 
       ORDER BY p.created_at DESC 
       LIMIT 4
     ) q
on u.user_id=q.user_id

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