1

Having an issue with this query. (mySQL)

I have a primary key (id) and I want to either insert a new value if the conditions don't exist OR update the existing:

INSERT into records (name, value, p_id, c_id) 
VALUES ('Store', 'TX', 1188913, 1133) 
ON DUPLICATE KEY UPDATE name = 'TX' WHERE p_id = 6188002 and c_id = 77102

So in this case, I would have a record as such that already exists:

id = 10235192
name = 'Store'
value = 'AL'
p_id = 6188002
c_id = 77102

And I would hope that that record is updated from value = 'AL' to 'TX'

But all I'm seeing is a new record inserted. What am I doing wrong?

4

2 回答 2

2

您应该UNIQUE在复合列上指定一个约束INSERT...ON DUPLICATE KEY UPDATE才能工作。

ALTER TABLE records ADD CONSTRAINT tb_uq UNIQUE (p_id, c_id)

andWHERE子句是不需要的。

INSERT into records (name, value, p_id, c_id) 
VALUES ('Store', 'TX', 1188913, 1133) 
ON DUPLICATE KEY UPDATE value = 'TX'
于 2013-07-20T17:45:15.717 回答
0

我有同样的问题,答案可以在这里找到。

使用 MySQL 进行条件重复键更新

实际的答案是WHEREMySQL 不支持该子句,您需要使用IF条件。

像这样的东西:

INSERT INTO daily_events
(created_on, last_event_id, last_event_created_at)
VALUES
('2010-01-19', 23, '2010-01-19 10:23:11')
ON DUPLICATE KEY UPDATE
last_event_id = IF(last_event_created_at < VALUES(last_event_created_at),     VALUES(last_event_id), last_event_id),
last_event_created_at = IF(last_event_created_at < VALUES(last_event_created_at), VALUES(last_event_created_at),   last_event_created_at);
于 2016-08-04T11:17:59.630 回答