我有一个像这样的表测试:
real_id name active
1 A 0
2 B 1
3 C 1
4 D 1
5 E 0
6 F 1
我要找的是:
选择有效列= 1的行,最后只从中获取一个随机
我试过了:
/*get the max count from recordset*/
SET @rows_count = (SELECT COUNT(*) FROM test WHERE active = 1);
set @fakeId = 0;
SELECT * FROM test, (
SELECT *, @fakeId := @fakeId + 1 AS fake_id,
(ROUND((RAND() * (@rows_count-1))+1)) AS random_nr
FROM test
WHERE active = 1
) AS total
WHERE total.fake_id = total.random_nr;
LIMIT 1;
乍一看它似乎运作良好,但如果我尝试过几次,我不时没有结果
解决
我通过计算select到变量
之外的random_nr来解决它们SET @random_nr = (ROUND((RAND() * (@rows_count-1))+1));
在WHERE子句中
WHERE total.fake_id = @random_nr;
答案 0 :(得分:1)
select * from test where active = 1 order by rand() limit 1