如果存在那么

时间:2012-07-19 10:15:54

标签: mysql if-statement insert exists

这很直接,但我找不到答案。如果组合确实存在,则UPDATE,否则INSERT。

IF EXISTS(SELECT customer_id FROM payment_conditions WHERE customer_id = 2 AND shipping_company_id = 1) 

THEN
UPDATE payment_conditions SET payment_condition = "pay in full" WHERE customer_id = 2  AND shipping_company_id = 1;

ELSE
INSERT INTO payment_conditions customer_id, shipping_company_id, payment_condition, active VALUES (2,1,"some value",1);


END IF

5 个答案:

答案 0 :(得分:2)

如果你有一个唯一的密钥(shipping_company_id,customer_id),你可以使用:

INSERT INTO payment_conditions 
SET customer_id = 2,
  shipping_company_id = 1,
  payment_condition = 'some value',
  active = 1
ON DUPLICATE KEY UPDATE payment_condition = 'pay in full'

答案 1 :(得分:2)

您应该将customer_idshipping_company_id设置为外键,以便您可以使用

INSERT INTO payment_conditions
    customer_id, shipping_company_id, payment_condition, active
VALUES (2, 1, "some value", 1)
ON DUPLICATE KEY UPDATE payment_condition = "pay in full"

答案 2 :(得分:1)

INSERT INTO payment_conditions (customer_id, shipping_company_id, payment_condition, active) 
VALUES (2,1,"some value",1)
ON DUPLICATE KEY UPDATE payment_condition = "pay in full"

答案 3 :(得分:1)

或发出两个语句(N.B.,UPDATE优先),并取消条件逻辑。如果行不存在,UPDATE将不起作用。如果您的密钥恰好与customer_id + shipping_company不同,那么这应该有用。

UPDATE payment_conditions SET payment_condition = "pay in full" 
WHERE customer_id = 2  AND shipping_company_id = 1;

然后

INSERT INTO payment_conditions 
(customer_id
, shipping_company_id
, payment_condition
, active) 
VALUES (2,1,"some value",1)
where not exists 
(select * FROM payment_conditions 
   WHERE customer_id = 2 AND shipping_company_id = 1);

答案 4 :(得分:0)

在SQL Server中使用merge语句 - 看起来这些答案意味着MySQL语法。您没有说明数据库的味道,但是在SQL Server上建议使用Merge。