2011-11-09 124 views
1

我現在有這個解決方案隨機條目:選擇從MySQL與where子句

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)快速選擇隨機條目?

回答

6

嘗試使用ORDER BY子句。試試這個:

SELECT COUNT(user_id) FROM bases WHERE user_id = " + userId + " AND is_valid = 1 ORDER BY RAND() LIMIT 1 

這將返回表中的一個隨機行。

0

我不明白你正在嘗試做的,但是這可能會幫助你(根據你的問題):

SELECT * 
FROM bases 
WHERE is_valid=1 AND user_id = <user_id> 
ORDER BY RAND() 
LIMIT 1;