在mysql中查询10条不重复的数据,使用以下:
SELECT * FROM `tableName` ORDERBY RAND() LIMIT 10
就可以了。但是真正测试一下才发现这样效率非常低。一个21万余条的库,查询10条数据,居然要10秒以上
搜索Google,网上基本上都是查询max(id) * rand()来随机获取数据。
SQL语句如下:
SELECT * FROM `fb_tb_goods` AS t1 JOIN (SELECT ROUND(RAND() * ((SELECT MAX(id) FROM `fb_tb_goods` WHERE status in (1,3) AND cj_level in (2,3) )-(SELECT MIN(id) FROM `fb_tb_goods` WHERE status in (1,3) AND cj_level in (2,3)))+(SELECT MIN(id) FROM `fb_tb_goods` WHERE status in (1,3) AND cj_level in (2,3))) AS aid) AS t2 WHERE t1.id >= t2.aid and t1.status in (1,3)ORDER BY t1.id LIMIT 16
我测试了一下,需要0.5秒,速度也不错,但是跟上面的语句还是有很大差距。总觉有什么地方不正常。
于是我把语句改写了一下。
SELECT * FROM `fb_tb_goods` AS t1 JOIN (SELECT ROUND(RAND() * ((SELECT MAX(id) FROM `fb_tb_goods`)-(SELECT MIN(id) FROM `fb_tb_goods`))+(SELECT MIN(id) FROM `fb_tb_goods`)) AS aid) AS t2 WHERE t1.id >= t2.aid and t1.status in (1,3) ORDER BY t1.id LIMIT 26;
这下,效率又提高了,查询时间只有0.01秒
最后,再把语句完善一下,加上MIN(id)的判断。我在最开始测试的时候,就是因为没有加上MIN(id)的判断,结果有一半的时间总是查询到表中的前面几行。
The End
网友评论