mysql隨機抽取數據


 
--
SELECT * FROM table_name ORDER BY rand() LIMIT 5;

-- 較慢
SELECT * FROM `table`
WHERE id >= (SELECT floor( RAND() * ((SELECT MAX(id) FROM `table`)-(SELECT MIN(id) FROM `table`)) + (SELECT MIN(id) FROM `table`)))
ORDER BY id LIMIT 1;

-- 快  `table 有 id 字段
SELECT *
FROM `table` AS t1 JOIN (SELECT ROUND(RAND() * ((SELECT MAX(id) FROM `table`)-(SELECT MIN(id) FROM `table`))+(SELECT MIN(id) FROM `table`)) AS id) AS t2
WHERE t1.id >= t2.id
ORDER BY t1.id LIMIT 1;

-- 快  `table 沒有有 id 字段
select * from (select @rownum:=@rownum + 1  as id,value from `table`,(select @rownum:=0) as a) as t1 join (
    select round( rand() * ( 
    (select max(b.id) from (select @rownum_max:=@rownum_max + 1  as id,value from `table`,(select @rownum_max:=0) as a) as b ) -
    (select min(b.id) from (select @rownum_min:=@rownum_min + 1  as id,value from `table`,(select @rownum_min:=0) as a) as b )
    )) + 
    (select min(b.id) from (select @rownum_min1:=@rownum_min1 + 1  as id,value from `table`,(select @rownum_min1:=0) as a) as b ) as id
) as t2
on t1.id>= t2.id
order by t1.id limit 1 

 

缺點: 

每次查詢后會獲得連續的n條數據

解決辦法:

每次查一條數據,重復查詢n 次

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM