我正在尝试编写一个查询,它将在0到9999之间插入一个随机值INTO表,而这个随机值尚未存在。 但是,我写的没有作品。看起来WHERE子句不适用于INSERT,我的SQL服务器无法执行IF NOT EXISTS查询。我不知道,这是不正确的吗? 我该怎么办?我的问题有解决方案吗? (我正在使用MySQL)
SET @rand = ROUND(RAND() * 9999);
IF NOT EXISTS (SELECT `num` FROM `nums` WHERE `num` = @rand)
INSERT INTO `nums` (`num`) VALUES (@rand);
答案 0 :(得分:1)
你可以这样做:MySQL: Insert record if not exists in table
INSERT INTO `nums` (`num`)
SELECT *
FROM
(SELECT @rand) AS q
WHERE NOT EXISTS
(SELECT `num`
FROM `nums`
WHERE `num` = @rand);
答案 1 :(得分: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
答案 2 :(得分: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
时,如果已存在,则不会插入行。