2013-03-18 165 views
1

我想寫一個查詢,它將插入一個表中0到9999之間的隨機值,而這個隨機值還沒有存在那裏。 但是,沒有我寫的作品。看起來像WHERE子句不適用於INSERT,並且我的SQL服務器無法執行IF NOT EXISTS查詢。我不知道這是不正確的嗎? 我該怎麼辦?有沒有解決我的問題? (我使用MySQL)爲什麼IF NOT EXISTS語句不起作用?

SET @rand = ROUND(RAND() * 9999); 
IF NOT EXISTS (SELECT `num` FROM `nums` WHERE `num` = @rand) 
    INSERT INTO `nums` (`num`) VALUES (@rand); 
+1

的MySQL或Oracle?他們完全不同。 – Mat 2013-03-18 12:29:40

+2

IF語句只適用於TSQL和PL/SQL。如果你只是執行查詢,那是行不通的。您必須將該邏輯放入執行代碼中。 – rbedger 2013-03-18 12:30:01

+0

我該怎麼做?我正在使用與當前版本的WampServer和XAMPP一起使用的MySQL版本。 – user2182300 2013-03-18 13:18:51

回答

0

使用這樣的存儲過程試試:

CREATE PROCEDURE my_sp() 
BEGIN 
SET @rand = ROUND(RAND() * 9999); 
IF NOT EXISTS (SELECT `num` FROM `nums` WHERE `num` = @rand) THEN 
    INSERT INTO `nums` (`num`) VALUES (@rand); 
END IF; 
END 
0

使用之類的語句IF屬於像一個存儲過程的代碼塊中。你將無法在mysql提示符下執行它。

如果你只是想插入一個隨機值,這是以前沒有的你也可以做到這一點通過

 
mysql> create table nums(num int, unique key(num)); 
Query OK, 0 rows affected (0.05 sec) 

mysql> insert ignore into nums >select round(rand()*9999);> 
Query OK, 1 row affected (0.01 >sec)> 
Records: 1 Duplicates: 0 Warn>ings>: 0> 

mysql> insert ignore into nums select round(rand()*9999); 
Query OK, 1 row affected (0.00 sec) 
Records: 1 Duplicates: 0 Warnings: 0 

mysql> insert ignore into nums select round(rand()*9999); 
Query OK, 1 row affected (0.00 sec) 
Records: 1 Duplicates: 0 Warnings: 0 

mysql> insert ignore into nums select round(rand()*9999); 
Query OK, 1 row affected (0.00 sec) 
Records: 1 Duplicates: 0 Warnings: 0 

mysql> select * from nums; 
+------+ 
| num | 
+------+ 
| 5268 | 
| 9075 | 
| 9114 | 
| 9768 | 
+------+ 
4 rows in set (0.00 sec) 

mysql> 

隨着insert ignore,如果它已經存在,它不會插入一行。