我的桌子看起来有点像这样
CREATE TABLE Foo (
UserAction VARCHAR(20),
JoiningDate DATETIME,
JoiningTime TIME
);
它包含以下记录:
UserAction JoiningDate JoiningTime
---------- ------------------- -------------
Pending 2018-01-14 00:00:00 20:00:00
Pending 2018-01-15 00:00:00 16:00:00
Pending 2018-01-16 00:00:00 16:00:00
Pending 2018-01-16 00:00:00 20:00:00
Pending 2018-01-17 00:00:00 16:00:00
现在我想更新所有记录:
JoiningDate
大于2018-01-16
2018-01-16
,则JoiningTime
为18:00:00
或以上这是我最终的期望输出:
UserAction JoiningDate JoiningTime
---------- ------------------- -------------
Pending 2018-01-14 00:00:00 20:00:00
Pending 2018-01-15 00:00:00 16:00:00
Pending 2018-01-16 00:00:00 16:00:00
DONE 2018-01-16 00:00:00 20:00:00
DONE 2018-01-17 00:00:00 16:00:00
目前,我已经编写了两个不同的查询来实现这一目标:
UPDATE foo SET UserAction = 'DONE' WHERE JoiningDate > '2018-01-16 00:00:00';
UPDATE foo SET UserAction = 'DONE' WHERE JoiningDate = '2018-01-16 00:00:00' AND JoiningTime >= '18:00:00';
它工作正常。我的问题是,有没有办法只使用一个查询来实现相同的目标?
答案 0 :(得分:1)
只需使用适当的WHERE
子句:
UPDATE foo
SET UserAction = 'DONE'
WHERE
JoiningDate > '2018-01-16' OR
(JoiningDate = '2018-01-16' AND JoiningTime >= '18:00:00');
这确切地符合您的要求,即更新加入日期大于2018-01-16
的所有记录,或者加入日期为2018-01-16
且加入时间为18:00:00
或更晚。您的查询实际上做了不同的事情,但我已根据您所写的内容做出回答。
答案 1 :(得分:0)
update `Foo`
SET UserAction = 'Done'
where date(JoiningDate) > '2018-01-16' AND JoiningTime >= '18:00:00'
这是你的要求吗?为什么你需要JoiningDate =' 2018-01-16' AND JoiningTime> =' 18:00:00'
答案 2 :(得分:0)
指定日期类型,删除时间戳会更好:
UPDATE Foo
SET UserAction = 'DONE'
WHERE DATE(JoiningDate) > '2018-01-16'
OR (DATE(JoiningDate) = '2018-01-16' AND JoiningTime >= '18:00:00');