2010-09-16 60 views
1

我測試了一個查詢在MySQL中得到一個隨機整數,我注意到了這個問題:混合RAND()和UNION給出隨機rowcount?

mysql> SELECT FLOOR(0 + (RAND() * 5)) UNION SELECT FLOOR(0 + (RAND() * 5)) UNION SELECT FLOOR(0 + (RAND() * 5)); 
+-------------------------+ 
| FLOOR(0 + (RAND() * 5)) | 
+-------------------------+ 
|      1 | 
|      2 | 
|      4 | 
+-------------------------+ 
3 rows in set (0.00 sec) 

mysql> SELECT FLOOR(0 + (RAND() * 5)) UNION SELECT FLOOR(0 + (RAND() * 5)) UNION SELECT FLOOR(0 + (RAND() * 5)); 
+-------------------------+ 
| FLOOR(0 + (RAND() * 5)) | 
+-------------------------+ 
|      4 | 
+-------------------------+ 
1 row in set (0.00 sec) 

mysql> SELECT FLOOR(0 + (RAND() * 5)) UNION SELECT FLOOR(0 + (RAND() * 5)) UNION SELECT FLOOR(0 + (RAND() * 5)); 
+-------------------------+ 
| FLOOR(0 + (RAND() * 5)) | 
+-------------------------+ 
|      1 | 
|      4 | 
|      0 | 
+-------------------------+ 
3 rows in set (0.00 sec) 

我似乎得到行的結果集中的隨機數!那裏有3 UNION ed SELECT s。到底是怎麼回事?我在想,從蘭特語句的結果也許有沒有因爲RAND()的元組,但沒有任何意義 - 應該有一些結果,一個NULL至少!

mysql> select version(); 
+-------------------+ 
| version()   | 
+-------------------+ 
| 5.0.51a-24+lenny4 | 
+-------------------+ 
1 row in set (0.00 sec) 

回答

3

UNION消除了重複結果,因爲它是一個集合運算符。如果您想保留重複項,請使用UNION ALL。也許我錯誤地理解了你的問題,但是這看起來正是我期望的查詢結果的類型。

+0

@ user57567567567:使用'UNION ALL',就像我說的 – recursive 2010-09-16 14:40:11

+0

一套明智的運營商意味着它會影響整個結果集? – user151841 2010-09-16 14:40:31

+0

set-wise表示它在集合上操作。集合中不能有重複的元素。 – recursive 2010-09-16 14:44:54