jeudi 17 novembre 2016

Get random single row from mysql table with enumerated rows

I've got a table with auto-incremented ID in Mysql. I am always adding to this table, never deleting and setting the ID value to NULL so that I am pretty sure there are no holes. This is the table structure:

CREATE TABLE mytable ( id smallint(5) unsigned NOT NULL AUTO_INCREMENT, data1 varchar(200) DEFAULT NULL, data2 varchar(30) DEFAULT NULL, PRIMARY KEY (id), UNIQUE KEY data (data1,data2) )

I want to pick up a random row from the table. I am using this:

select * from mytable where id=(select floor(1 + rand() * ((select max(id) from mytable) - 1)));

But sometimes I get nothing, sometimes one row, sometimes two. Replacing max(id) with count(*) or count(id) did not help. I understand it may be because rand() is evaluated for each row. As suggested in a similar question, I used this query:

select * from mytable cross join (select @rand := rand()) const where id=floor(1 + @rand*((select count(*) from mytable)-1));

But I still get an empty set sometimes. Same goes for this:

select * from mytable cross join (select @rand := rand()) const where id=floor(@rand*(select count(*) from mytable)+1);

I am looking for a fast way to do this, so that it won't take a long on big tables. ORDER BY rand() LIMIT 1 is not an option for me. Can't that be done with one query, can be?




Aucun commentaire:

Enregistrer un commentaire