首页 > 数据库 >Mysql 随机查询10条数据效率最快的查询方法

Mysql 随机查询10条数据效率最快的查询方法

时间:2023-03-15 10:23:37浏览次数:59  
标签:10 MIN 查询方法 topic Mysql RAND id SELECT

1)使用join 和 rand() 耗时 0.009

SELECT
    *
FROM
    `t_topic` AS t1
JOIN (
    SELECT
        ROUND(
            RAND() * (
                (SELECT MAX(id) FROM `t_topic`) - (SELECT MIN(id) FROM `t_topic`)
            ) + (SELECT MIN(id) FROM `t_topic`)
        ) AS id
) AS t2
WHERE
    t1.id >= t2.id
ORDER BY
    t1.id
LIMIT 10;

2) 下面这条比上面那个还要慢几秒

SELECT * FROM `t_topic`
WHERE id >= (SELECT floor( RAND() * ((SELECT MAX(id) FROM `t_topic`)-(SELECT MIN(id) FROM `t_topic`)) + (SELECT MIN(id) FROM `t_topic`)))
ORDER BY id LIMIT 10;

3)或者使用下面这个也可以测试也是 耗时0.0012

SELECT
    *
FROM
    `t_topic`
WHERE
    id >= (
        SELECT
            floor(
                RAND() * (SELECT MAX(id) FROM `t_topic`)
            )
    )
ORDER BY
    id
LIMIT 10;

链接来源:https://www.bbsmax.com/A/MyJxN2q1dn/

标签:10,MIN,查询方法,topic,Mysql,RAND,id,SELECT
From: https://www.cnblogs.com/hefeng2014/p/17217545.html

相关文章