更新条目要设置的IF值不同,否则仅更新1列

时间:2014-09-19 07:26:01

标签: mysql

我有桌子:

job  | startDate           | EndDate             | Status 
3221 | 2014-08-12 12:00:00 | 2014-08-12 15:00:00 | 1

我有两个案例: 这包含相同的startDate和EndDate值,这意味着我不需要在条目上进行实际更新:

UPDATE jobs SET startDate='2014-08-12 12:00:00', EndDate='2014-08-12 15:00:00' WHERE job=3221

在这种情况下,我的值​​EndDate略有不同(也可能是startDate或两者兼而有之) 所以我必须更新实际更改的值(不相同),并将STATUS从1更新为0(因为以前的更新值不一样)任何想法如何在一个查询中实现?

UPDATE jobs SET startDate='2014-08-12 12:00:00', EndDate='2014-08-13 19:00:00' WHERE job=3221

3 个答案:

答案 0 :(得分:1)

用例陈述

UPDATE Table
     Case WHEN <Condition>              
          THEN set statue=0 
          ELSE set status=1 END

答案 1 :(得分:1)

CREATE TABLE t
    (`job` int, `startDate` datetime, `EndDate` datetime, `Status` int)
;

INSERT INTO t
    (`job`, `startDate`, `EndDate`, `Status`)
VALUES
    (3221, '2014-08-12 12:00:00', '2014-08-12 15:00:00', 1),
    (3222, '2014-08-12 12:00:00', '2014-08-12 15:00:00', 1)
;

UPDATE t
SET Status = IF(startDate = '2014-08-12 12:00:00' AND EndDate = '2014-08-12 15:00:00', 1, 0),
startDate = '2014-08-12 12:00:00',
EndDate = '2014-08-12 15:00:00'
WHERE job = 3221;

UPDATE t
SET Status = IF(startDate = '2014-08-12 12:00:00' AND EndDate = '2014-08-13 19:00:00', 1, 0),
startDate = '2014-08-12 12:00:00',
EndDate = '2014-08-13 19:00:00'
WHERE job = 3222;

SELECT * FROM t;

|  JOB |                     STARTDATE |                       ENDDATE | STATUS |
|------|-------------------------------|-------------------------------|--------|
| 3221 | August, 12 2014 12:00:00+0000 | August, 12 2014 15:00:00+0000 |      1 |
| 3222 | August, 12 2014 12:00:00+0000 | August, 13 2014 19:00:00+0000 |      0 |

答案 2 :(得分:1)

这是一个更简单的版本:

UPDATE jobs 
SET    StartDate = '2014-08-12 12:00:00', 
       EndDate = '2014-08-13 19:00:00',
       `Status` = DATE(StartDate) = DATE(EndDate)       -- returns 1 (true) or 0
WHERE  job = 3221