I'm trying to insert a new row, but if the key already exists, I want to update the row ONLY if a certain other value is in the table is different. Is this possible in a mysql query/statement?
My table consist of the following columns: hat, mittens, name, last_update
hat+mittens make up the unique index (say the values for "hat" and "mittens" are colors)
Let's assume this is already in the table:
1. hat=blue mittens=green name=george last_update=tuesday 2. hat=red mittens=green name=bill last_update=monday
On a new key, I want to insert as usual. On duplicate key, I want to do an update ONLY IF the name changes, otherwise ignore. The reason for this is that I want to preserve the last_update value (timestamp).
hat=yellow mittens=purple name=jimmy -- insert new row hat=blue mittens=green name=george -- ignore hat=blue mittens=green name=betty -- update row
Is this possible without using separate statements to first look up the existing row, compare values and then issue an update if necessary? If so, what would be the syntax?
Thanks for your responses. I tried all of them. Indeed, using just a simple UPDATE statement like
update tbl set name='george' where hat='blue' and mittens='green'
results in no rows being updated. But, using either
INSERT INTO tbl (hat,mittens,name) VALUES ('blue','green','george') ON DUPLICATE KEY UPDATE name='george';
or
INSERT INTO tbl (hat, mittens, name) VALUES ('blue','green','george') ON DUPLICATE KEY UPDATE name=CASE WHEN name <> VALUES(name) THEN VALUES(name) ELSE name END;
somehow results in the row being updated (and the timestamp changed).
FWIW, this is the table I'm using:
CREATE TABLE `tbl` (
`hat` varchar(11) default NULL,
`mittens` varchar(11) default NULL,
`name` varchar(11) default NULL,
`stamp` timestamp NOT NULL default CURRENT_TIMESTAMP on update CURRENT_TIMESTAMP,
UNIQUE KEY `clothes` (`hat`,`mittens`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1
MySQL is version 4.1.22 (perhaps this matters?) Again, my appreciation for all of the replies.