0

How do i update only if a second condition is true, it seems my version of mysql doesnt allow a WHERE at the end of ON DUPLICATE syntax.

INSERT INTO `proxies` (`proxy`,`response`,`PAYMENT`,`type`,`country`,`status`,`tier`,`last_checked`,`last_active`,`response_time`) 
VALUES ('111.9.204.96:8123','200','coolproxies','anon','China','active','3','1400624136','1400624136','1.577639') 
ON DUPLICATE KEY UPDATE `response`='200',`response_time`='1.577639',`type`='anon',`country`='China',`status`='active',`tier`='2',`last_checked`='1400624137'

this works ok, but I need to only update when WHERE last_checked < '1400624137' is true.

This is what the query that does this looks like.

INSERT INTO `proxies` (`proxy`,`response`,`PAYMENT`,`type`,`country`,`status`,`tier`,`last_checked`,`last_active`,`response_time`)
VALUES ('207.204.249.193:21320','200','scanner','anon','United States','active','1','1400633866','1400633866','1.59696')
ON DUPLICATE KEY UPDATE
`response_time` = IF(`last_checked` < '1400633866', '1.59696', `response_time`),
`status` = IF(`last_checked` < '1400633866', 'active', `status`),
`last_checked` = IF(`last_checked` < '1400633866', '1400633866', `last_checked`),
`last_active` = IF(`last_checked` < '1400633866', '1400633866', `last_active`);
Evan
  • 1,683
  • 7
  • 35
  • 65

2 Answers2

0

I think you need to do this as two statements:

 update . . . 
 where last_checked < '1400624137';

 insert ignore into proxies(. . .);

(or use on duplicate key update to do nothing).

Gordon Linoff
  • 1,242,037
  • 58
  • 646
  • 786
0

An alternative to doing it in 2 queries as @GordonLinoff mentioned, is to use the method described in this related question you can use an IF to update based on a condition.

INSERT INTO `proxies` (...) 
VALUES (...) 
ON DUPLICATE KEY UPDATE
  my_column = IF(last_checked < '1400624137', VALUES(my_column), my_column)

Basically what the IF does is when TRUE then update the field to the new value, otherwise if FALSE set it to the current value, which means no change to your existing data.

Community
  • 1
  • 1
Alex.Ritna
  • 1,957
  • 2
  • 16
  • 24