我想要的是什么:
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
);
由于子查询中的LIMIT
,这不起作用。我想保留子查询的顺序,但我希望得到username
和last_activity
而不是user_id
。
有什么建议我能做到这一点吗?
答案 0 :(得分:0)
用视图替换子查询:
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);
答案 1 :(得分:0)
为什么要用JOIN
来做?似乎没有性能影响,因为WHERE
和LIMIT
子句是相同的。它赢得了JOIN
整个表格:
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
答案 2 :(得分:0)
您可以将join
用于表格和子查询,而不是使用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