我有桌子'用户',有大约100万用户。我有查询选择像这样的在线用户
select *, CASE WHEN abstime ( last_login_time + 600 ) >= now ( )
THEN 3 ELSE 1 END AS onsitegen
from user where blocked=0 order by onsitegen desc limit 3;
但它太慢了,我理解为什么。这是因为我使用了onsitegen的订单。
但是您可以选择另一种选择在线用户的方法吗?
答案 0 :(得分:1)
首先创建一个索引:
CREATE INDEX abc ON users( blocked, last_login_time );
然后尝试此查询:
SELECT *
FROM (
SELECT U.*, 3 As onsitegen
from users u
WHERE u.blocked = 0
AND u.last_login_time >= now() - 600 * interval '1' second
LIMIT 3
) x
UNION ALL
SELECT *
FROM (
SELECT U.*, 1 As onsitegen
from users u
WHERE u.blocked <> 0
AND u.last_login_time < now() - 600 * interval '1' second
LIMIT 3
) y
ORDER BY onsitegen DESC
LIMIT 3