How can i select 1 random number from database thats ID is autoincrement field.I have 25,000[ID] records in database.Each every time select one new random ID. How can get it.
You can use the following query to generate a random number between 0 and COUNT
-1 of your table rows:
SELECT ROUND((RAND() * (SELECT COUNT(*) FROM mytable)-1))
Then use this number as an offset in the LIMIT
clause of your query to get a random row from your table.
Using a prepared statement , you can do:
SET @offset = (SELECT ROUND((RAND() * (SELECT COUNT(*) FROM mytable)-1)));
PREPARE STMT FROM 'SELECT * FROM mytable LIMIT ?, 1';
EXECUTE STMT USING @offset;
Note that use of the prepared statement is mandatory since as documented in the manual :
LIMIT takes one or two numeric arguments, which must both be non-negative integer constants ( except when using prepared statements ).
Use following sql(slow)
'SELECT * FROM tablename ORDER BY RAND() LIMIT 1'
or you can use(fast)
SELECT * FROM myTable, (SELECT FLOOR(MAX(myTable.id) * RAND()) AS randId FROM myTable) AS someRandId WHERE myTable.id = someRandId.randId
The inner SELECT gives you a random id in the right range. The outer SELECT looks for the right row in the table.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.