简体   繁体   中英

mysql Rand() function cause unexpected multirow results

When I try to get random row from table by id using RAND() function I get unexpected unstable results. The following query (where id column is primary key) returns 1, 2 or even more rows:

查询和结果

I tried next variant as well which produces same result:

SELECT id, word FROM words WHERE id = FLOOR(RAND() * 1000)

I found another solution for my task:

SELECT id, word FROM words ORDER BY RAND() LIMIT 1

But I want to know why MySQL behavior is so unexpected with using so elementary functionality. It scares me.

I experimented in different IDE with the same results.

The behavior is not unexpected. The RAND() function is evaluated per-row:

SELECT RAND() FROM sometable LIMIT 10

+----------------------+
| RAND()               |
+----------------------+
|   0.7383128467372738 |
|   0.6141578719151746 |
|   0.8558508500976961 |
|   0.4367806654766022 |
|   0.6163508078235674 |
|   0.7714120734216757 |
|   0.0080079743713214 |
|   0.7258036823252251 |
|   0.6049945192458057 |
|   0.8475615799869984 |
+----------------------+

Keeping this in mind, this query:

SELECT * FROM words WHERE id = FLOOR(RAND() * 1000)

means that every row with id between 0 and 999 has 1/1000 probability of being SELECTed!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM