【问题标题】:Select random record from mysql with multiple filters使用多个过滤器从 mysql 中选择随机记录
【发布时间】:2016-08-29 01:12:26
【问题描述】:

我知道这已被讨论过很多次,但我的研究并没有帮助我解决我的问题。

我有一个包含大约 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 列进行索引。

【问题讨论】:

  • 看看this
  • 我在写到这里之前就试过了。但这对我没有帮助,因为我的 WHERE 过滤器
  • 3K 行在哪个表中?另一个表有多少行?
  • posts 表中的 3k 行。记录表有 8k 行。

标签: mysql performance random mysqli


【解决方案1】:

我不会使用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 上的另一个索引

【讨论】:

  • 我认为这是“where id in”的替代方案。我的查询是“id not in”
  • @ozn WHERE id IN 将是 INNER JOIN,而这是使用 LEFT JOIN .... WHERE NULL,相当于 WHERE id NOT IN
  • 我会试试这个并告诉结果。顺便说一句,您对表格类型有何看法? innodb 可以执行此操作吗?
  • 您的查询和我的一样慢。没有显着的加速:(
  • @ozn 你能用你的索引更新你的问题吗?
猜你喜欢
  • 1970-01-01
  • 2012-12-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-01-26
  • 2011-09-05
相关资源
最近更新 更多