1

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.

H. Pauwelyn
  • 13,575
  • 26
  • 81
  • 144
venkatesh
  • 3
  • 6
  • Please elaborate your question. – Nilambar Sharma Jun 20 '15 at 06:51
  • In my database table ID[auto increment],product name two fields then total product is extractly 30,000 records.Now 30,000 members are there and now each members show one PRODUCT randomly through ID without repeated ID. thats it.This information is enough for you. – venkatesh Jun 20 '15 at 07:08

2 Answers2

1

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).

Demo here

Community
  • 1
  • 1
Giorgos Betsos
  • 71,379
  • 9
  • 63
  • 98
0

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.

Ravi Kumar Mistry
  • 1,063
  • 1
  • 13
  • 24