大数据SQL随机查询
PHP SQL随机查询数据小的话还是用rand() 比较方面。如果数据太多的话,可以建立临时附表查询。或者用join链接。rand()在大数据上有很大的概率就直接挂掉!
$sql1 = “SELECT * FROM `表名` AS t1 JOIN (SELECT ROUND(RAND() * ((SELECT MAX(id) FROM `表名`)-(SELECT MIN(id) FROM `表名`))+(SELECT MIN(id) FROM `表名`)) AS id) AS t2 WHERE t1.id >= t2.id ORDER BY t1.id LIMIT 1”;
添加下具体查询更会提高速度
$sql1 = “SELECT `具体字段` FROM `表名` AS t1 JOIN (SELECT ROUND(RAND() * ((SELECT MAX(id) FROM `表名`)-(SELECT MIN(id) FROM `表名`))+(SELECT MIN(id) FROM `表名`)) AS id) AS t2 WHERE t1.id >= t2.id ORDER BY t1.id LIMIT 1”;
不过,如果查询多条的话,数组和SQL直接取出的还是有点区别!就因为这个问题折腾了不少时间!
多条出来的数组类似:
array(
[0]=>array(
[id]=>id
[0]=>id
[name]=>name
[1]=>name
[2]=>id
)
[1]=>array(
[id]=>id
[0]=>id
[name]=>name
[1]=>name
[2]=>id
)
)
取值方面不大好取。如果用这段建议还是先print一下看看数组的格式在决定怎么取具体值!