tags:

views:

61

answers:

2
select id, name from customer order by random() limit 5;

The above query select random records. However it repeats rows. I just want to select a single row each time without repeating. Say i have id 1 to 5. For first time i want to select 1, second time the query displays 2 then 3,4 & 5. Once the sequence is completed it starts again with 1.

A: 
$query= "select id, name from customer order by id limit ".rand(1,5).",1"

Read more about using limit here: http://dev.mysql.com/doc/refman/5.0/en/select.html

RandyMorris
id | name--------+------------------------------------- 209096 | Pharmacy 204200 | Eyecare Center 185718 | Duffy PC 214519 | Shopko 162225 | Edward Jones 7609 | Back In Action Chiropractic CenterI use "select id, name from customer order by random()" There are 6 records i just want that when ever i query, i will get a unique row each time for six times and then it starts again or the records are ordered in a way that the top one did't repeat
jawad
if you are going to use a random line then you are going to have to remember which one was used and omit these record ids till none left, then reset.
RandyMorris
A: 

Since SELECT is an atomic operation, I don't think, that there is an easy solution. I also see two different problems that need to be solved:

selecting a single row without repeating a shown one. Basically you need to store the last line showed somewhere. If you have some application, that stores the current state, it might be an option, to save it as an external variable. The sketched solution is done in MySQL 5.0+:

First prepare a statement that will be executed later on and set a initial position for the query:

PREPARE STMT FROM 'SELECT id, name FROM customer LIMIT ?, 1';
SET @pos = 0;

You might want to add a defautl ordering to get a reliable result. Each time you want to get a single row, execute the statement by

EXECUTE STMT USING @pos; 
SELECT count(*) FROM customer INTO @max; 
SET @pos=(@pos+1)%@max;

The other thing is, that you want to read a random position. The only solution that I see right now, is to create a temporary table that either holds the content from customer ordered by random or that you create a temporary table holding all numbers from 0..@max and read the current position in the main table from the temporary table. If you have an application outside MySQL there might be more elegant ways to solve this.

frenkx