1

这很简单,但我找不到答案。如果组合确实存在,则更新,否则插入。

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
4

5 回答 5

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'
于 2012-07-19T10:21:18.253 回答
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"
于 2012-07-19T10:21:46.843 回答
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"
于 2012-07-19T10:21:19.713 回答
1

或者发出两条语句(NB 先更新),并取消条件逻辑。如果该行不存在,则 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);
于 2012-07-19T10:25:17.957 回答
0

在 SQL Server 中使用合并语句 - 看起来这些答案暗示了 MySQL 语法。您没有说明数据库风格,但 Merge 是在 SQL Server 上执行此操作的推荐方法。

于 2012-07-19T13:52:37.157 回答