我现在有这个解决方案:
rs = lState.executeQuery("SELECT FLOOR(RAND() * COUNT(*))
FROM bases
WHERE user_id = " + userId + " AND is_valid = 1");
rs.next();
count = rs.getInt(1);
rs = lState.executeQuery("SELECT id, server, server_port, server_ssl,
server_starttls, server_auth, email, password, auth_wholemail
FROM bases LIMIT " + count + ", 1");
但它不起作用,因为FLOOR(RAND() * COUNT(*))
不是is_valid = 1
的返回ID。
那么如何从MySQL whith where子句(其中is_valid = 1)中快速选择随机条目?
答案 0 :(得分:7)
尝试使用ORDER BY子句。试试这个:
SELECT COUNT(user_id) FROM bases WHERE user_id = " + userId + " AND is_valid = 1 ORDER BY RAND() LIMIT 1
这将从表中返回一个随机行。
答案 1 :(得分:0)
我不明白你在做什么,但这可能对你有所帮助(基于你的问题):
SELECT *
FROM bases
WHERE is_valid=1 AND user_id = <user_id>
ORDER BY RAND()
LIMIT 1;
答案 2 :(得分:0)