I know this was discussed many times but my research did not help me with my problem.
I have a table (innodb) with about 3k records. I need to pick 1 row random with some filters, which i do it like this:
select id, title, topic_id
from posts
where id not in
(select post_id from records where user_id='$my_id' and checked='1')
and topic_id='$topic_id' and status='1'
order by RAND() limit 1
This gives me the result i wanted. The problem is this takes too much time even with 3k records. It will get slower when records are increased.
I have to find a solution for this. Any suggestions?
Update: Both tables are indexed with id columns.
答案 0 :(得分:2)
我会使用where id not in
:
LEFT JOIN
SELECT id,
title,
topic_id
FROM posts p
LEFT JOIN records r
ON p.id = r.post_id
AND r.user_id='$my_id'
AND r.checked = '1'
WHERE p.topic_id='$topic_id'
AND status='1'
AND r.post_id IS NULL
ORDER BY RAND()
LIMIT 1;
有了这个,您需要posts.id
上的索引和records.post_id, records.user_id, records.checked
上的另一个索引