Random number in MySQL that does not repeat

-4

I have the following problem.

I need to make my select generate me randomly, but without being repeated.

I have placed an expression in the order by , and yet it still repeats itself.

Query:

SELECT preguntas.* FROM preguntas ORDER BY rand() LIMIT 1;
    
asked by Yoel Rodriguez 02.05.2017 в 19:52
source

2 answers

0

Look. If you only want to obtain only one element, it is difficult that they do not repeat themselves. The possible solutions that occur to me are:

  • You make the query with the list of questions you have already done with

    SELECT preguntas.* 
    FROM preguntas 
    WHERE preguntas.id NOT IN(1,4,6) 
    ORDER BY rand() 
    LIMIT 1;
    

    where 1, 4, 6 are the questions that have already been asked.

  • You determine the list of questions from before, so that they do not repeat themselves, something like ids de preguntas que se harán = {1,5,78,3,34,4,5,73} using the same query that you have:

    SELECT preguntas.* 
    FROM preguntas 
    ORDER BY rand() 
    LIMIT 10;
    

    Where 10 is the total number of questions you want for the Quiz or what you are doing.

For both cases you can save the list in the user session. An example with fixed data in PHP:

$_SESSION['preguntas'] = array (1, 6, 4, 12);

// dependiendo de tu marco de trabajo quedaría algo como 
$_SESSION['preguntas'] = Preguntas::getRandomQuestions(10);

Then in the first case, you add questions to the array, in the second case you will need another additional variable indicating which question it is. However, if the users' answers are stored in the database, you may only need to ask another question to verify which question the user is in.

Well, I put it as an answer, since I had put it as a comment: P

    
answered by 02.05.2017 / 22:04
source
0

But what do you want to be random, columns or rows ?. I did a quick test on my local BD and using ORDER BY rand() works great. What is the behavior you are expecting?

select tabla.* from tabla order by rand();

+-------+
| campo |
+-------+
| b     |
| a     |
| c     |
| d     |
+-------+

and if I run it again

+-------+
| campo |
+-------+
| d     |
| c     |
| a     |
| b     |
+-------+

And in case you want just one record, your code also works

select tabla.* from tabla order by rand() limit 1;
+-------+
| campo |
+-------+
| b     |
+-------+

again

+-------+
| campo |
+-------+
| c     |
+-------+
    
answered by 02.05.2017 в 21:51