[英]Select random record from mysql with multiple filters
我知道已經討論過很多次了,但是我的研究並沒有幫助我解決我的問題。
我有一個約3k記錄的表(innodb)。 我需要選擇一些過濾器隨機選擇1行,我這樣做是這樣的:
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
這給了我想要的結果。 問題是即使使用3k記錄也要花費太多時間。 記錄增加時,它將變慢。
我必須為此找到解決方案。 有什么建議么?
更新:兩個表都用id列索引。
我將使用LEFT JOIN
而不是使用where id not in
:
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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.