Select random ID between 2 and 4

Asked

Viewed 66 times

2

It is possible to randomly select the ID by placing, for example, the ID numbers that can be drawn (2/4)?

Note: Only one line of this selection should be returned.

I put this code but it wasn’t:

SELECT descricao
 FROM TABLE
 ORDER BY RAND ID (2,4)
 LIMIT 1;

1 answer

2


You can try to do it this way:

SELECT descricao
 FROM TABLE
 WHERE ID = FLOOR(RAND() * 3 + 2)
 LIMIT 1;

The function RAND() will return a random floating point number between 0 and 1, ie a decimal number. To limit the result between a specific number range, which includes both the minimum number and the maximum number, you make the following account:

FLOOR( RAND() * (max - min + 1) + min )

The function FLOOR() will disregard the decimal places, returning only the entire part of a decimal number.

Sources:
Mysql FLOOR() Function - w3resource
Mysql RAND() Function - w3resource
Mysql Rand() between 2 values Github

Browser other questions tagged

You are not signed in. Login or sign up in order to post.