$service = $this->common_model->get_records(
"select catalog_id from ".$this->db->dbprefix('shop_service').' as t1
JOIN (SELECT ROUND(RAND() * ((SELECT MAX(id) FROM '.$this->db->dbprefix('shop_service').')-(SELECT MIN(id) FROM '.$this->db->dbprefix('shop_service').'))+(SELECT MIN(id) FROM '.$this->db->dbprefix('shop_service').')) AS id) AS t2
where t1.id>t2.id and t1.is_trash=0 group by t1.catalog_id limit 5'
);
代码如下:
SELECT * FROM `table` WHERE id >= (SELECT floor(RAND() * (SELECT MAX(id) FROM `table`))) ORDER BY id LIMIT 1;
这下,效率又提高了,查询时间只有0.01秒
最后,再把语句完善一下,加上MIN(id)的判断。我在最开始测试的时候,就是因为没有加上MIN(id)的判断,结果有一半的时间总是查询到表中的前面几行。
完整查询语句是:
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;
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;
最后对这两个语句进行分别查询10次,
前者花费时间 0.147433 秒
后者花费时间 0.015130 秒
看来采用JOIN的语法比直接在WHERE中使用函数效率还要高很多。