jeudi 2 décembre 2021

MySQL random select doesn't return anything

I am trying to make a app that generates a random username. I have a simple table with just an ID and a name column. Basically:

| id | name | |-|-| | 1 | dude | | 2 | chill| etc

I want to select 3 random values from there. This is my attempt:

SELECT COUNT(id) INTO @count -- gets the length
FROM username_generator;
 
SELECT name FROM username_generator -- selects 3 names with random IDs
WHERE id IN (
    (FLOOR(RAND() * @COUNT)+1), 
    (FLOOR(RAND() * @COUNT)+1),
    (FLOOR(RAND() * @COUNT)+1)
);

The idea is that it counts the length and selects 3 IDs inside the length range.

The problem is that this sometimes returns NOTHING and I can't figure out why. The random numbers are always in the range and I have names in the table. Eg:

Normal:

enter image description here

Not normal:

enter image description here




Aucun commentaire:

Enregistrer un commentaire