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

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

Mysql 随机查询10条数据效率最快的查询方法
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;
Mysql 随机查询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

Mysql 随机查询10条数据效率最快的查询方法
SELECT
    *
FROM
    `t_topic`
WHERE
    id >= (
        SELECT
            floor(
                RAND() * (SELECT MAX(id) FROM `t_topic`)
            )
    )
ORDER BY
    id
LIMIT 10;

转自:https://www.cnblogs.com/*/p/8926371.html

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

上一篇:postgresql存储过程


下一篇:数据库(DDL、DML、DQL)