SELECT name
FROM random AS r1 JOIN
(SELECT (RAND() *
(SELECT MAX(id)
FROM random)) AS id)
AS r2
WHERE r1.id >= r2.id
ORDER BY r1.id ASC
LIMIT 1;
在查找MySQL的优化时,我想出了这个查询。但是,它并不完全符合我的目的,因为我想从我的数据库中提取随机用户,但我也有一个活动字段。所以我想确保“active = 1”,但我不确定在哪里将其插入此查询以使其正常工作。
答案 0 :(得分:3)
我认为应该这样做:
SELECT name
FROM random r1
JOIN (SELECT RAND()*MAX(id) randid
FROM random
WHERE active = 1) r2
WHERE r1.id >= r2.randid
AND r1.active = 1
ORDER BY r1.id
LIMIT 1
您需要在子查询和主查询中测试active = 1
。
答案 1 :(得分:1)
SELECT * FROM users WHERE active = 1 ORDER BY RAND() LIMIT 1;
虽然有more optimized alternatives to RAND()
,但我建议您从上面开始简化查询并稍后进行优化。