用case更新sql并更新值,无论哪种情况都是正确的

时间:2014-05-13 20:59:12

标签: mysql sql

UPDATE users SET log = CASE WHEN id = 2 THEN 1  ELSE 0 END WHERE r_id = 1  

这会更新2行的时间戳,其中一行是先前的log = 1,当前的日志是1。如何只更新当前的log = 1?

表格:

CREATE TABLE `users` (
  `sno` int(255) NOT NULL AUTO_INCREMENT,
  `id` varchar(255) NOT NULL,
  `r_id` varchar(255) NOT NULL,
  `log` int(11) NOT NULL,
  `last_login` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  PRIMARY KEY (`sno`)
) 



INSERT INTO `users` (`sno`, `id`, `r_id`, `log`, `last_login`) VALUES
(1, '1', '1', 0, '2014-05-13 14:44:09'),
(2, '2', '1', 0, '2014-05-13 14:45:07'),
(3, '3', '1', 0, '2014-05-13 14:44:09'),
(4, '4', '1', 0, '2014-05-13 14:44:09'),
(5, '5', '1', 0, '2014-05-13 15:19:23'),
(6, '6', '2', 1, '0000-00-00 00:00:00'),
(7, '7', '3', 1, '0000-00-00 00:00:00');

答案:

UPDATE users SET log = CASE WHEN id = 2 THEN 1  ELSE 0 END,last_login = CASE WHEN id = 2 THEN now()  ELSE last_login END WHERE r_id = 1  

2 个答案:

答案 0 :(得分:1)

您似乎在case中有两个条件,但只有一个then。以下是对你想要的猜测:

UPDATE users
    SET log = (CASE WHEN id = '2' AND last_login = now() THEN 1 
                    ELSE 0
               END)
    WHERE r_id = '1';

请注意,将last_loginnow()等值进行比较非常是危险的。你很可能永远不会得到一场比赛。也许是这样的事情:

UPDATE users
    SET log = (CASE WHEN id = '2' AND
                         last_login >= now() - interval 1 second
                    THEN 1 
                    ELSE 0
               END)
    WHERE r_id = '1';

编辑:

如果您只想更新满足这些条件的users中的最后一行,也许您想要:

UPDATE users
    SET log = (CASE WHEN id = '2' THEN 1 ELSE 0 END)
    WHERE r_id = '1'
    ORDER BY last_login DESC
    LIMIT 1;

答案 1 :(得分:0)

NOW()是一个函数,不应该在引号中:

UPDATE users SET log = CASE WHEN id = '2' THEN 1 AND last_login = NOW() ELSE 0 END WHERE r_id = '1'

通过引号你告诉MySQL,值是文字字符串" now()"而不是功能。