[英]sql if not exists () insert not working
This is my query: 这是我的查询:
IF NOT EXISTS (SELECT *
FROM teovecerdi
WHERE LocationName = 'Frankfurt'
AND StartDate = '14/02/2015'
AND EndDate = '17/02/2015'
AND Price = '2700')
INSERT INTO teovecerdi(LocationName, StartDate, EndDate, Price)
VALUES(?,?,?,?)
Can you tell me what's wrong with it? 你能告诉我这是怎么回事吗? I've also tried with BEGIN and END and it still gives me an error. 我也尝试过使用BEGIN和END,但仍然给我一个错误。
EDIT: I handle the parameters correctly. 编辑:我正确处理参数。
You can't use an IF
statement in a query, it can only be used in a stored procedure. 您不能在查询中使用IF
语句,只能在存储过程中使用它。
If you want to do a conditional INSERT
, you can use a SELECT
query that only returns a row when the condition is met. 如果要执行条件INSERT
,则可以使用SELECT
查询,该查询仅在满足条件时返回一行。
INSERT INTO teovecerdi(LocationName, StartDate, EndDate, Price)
SELECT ?, ?, ?, ?
FROM DUAL
WHERE NOT EXISTS (SELECT *
FROM teovecerdi
WHERE LocationName = 'Frankfurt'
AND StartDate = '14/02/2015'
AND EndDate = '17/02/2015'
AND Price = '2700')
您不能在查询或脚本中使用MySQL的过程语法(包括IF
这样的语句,以及迭代构造等)。
I am going to suggest a different approach. 我将建议一种不同的方法。 My guess is that you want LocationName, StartDate, EndDate, Price
to be unique. 我的猜测是您希望LocationName, StartDate, EndDate, Price
唯一。 So, let the database do the work for you: 因此,让数据库为您完成工作:
CREATE UNIQUE INDEX unq_teovecerdi_4 on teovecerdi(LocationName, StartDate, EndDate, Price);
Then just be careful to "ignore" errors when you do an insert. 然后,在插入时请小心“忽略”错误。 My preferred method is: 我的首选方法是:
INSERT INTO teovecerdi (LocationName, StartDate, EndDate, Price)
VALUES (?, ?, ?, ?)
ON DUPLICATE KEY UPDATE LocationName = VALUES(LocationName);
The ON DUPLICATE KEY
does nothing except absorb the error, when you attempt to insert a duplicate. 当您尝试插入重复项时, ON DUPLICATE KEY
除了吸收错误外不执行任何操作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.