1

是否有可能有一个查询来检查是否满足条件,并且取决于答案 a)INSERT或 b) UPDATE

(Mandar在回答中提出了更好的例子)

CASE 
   WHEN
      IF EXISTS (SELECT action FROM database where action = 'eat' AND user = 'me') 
      THEN  (UPDATE database set action = 'digest' where user = 'me')
   WHEN
      IF EXISTS (SELECT action FROM database where action = 'inhale' AND user = 'me') 
      THEN  (UPDATE database set action = 'exhale' where user = 'me')

   ELSE (INSERT INTO database (user,action) VALUES ('me','living'))
END CASE

它没有给出预期的结果。

4

3 回答 3

2

使用如果存在

IF EXISTS (SELECT action FROM database where action = 'eat' AND user = 'me') 
 THEN  (UPDATE database set action = 'digest' where user = 'me')

ELSE (INSERT INTO database (user,action) VALUES ('me','eat'))
于 2012-09-10T01:07:39.110 回答
1

如果(action, user)是表中的唯一键,则可以使用以下INSERT ... ON DUPLICATE KEY UPDATE语法来实现:

INSERT INTO database (user,action) VALUES ('me','eat')
ON DUPLICATE KEY UPDATE Action='digest';
于 2012-09-10T01:14:20.217 回答
0

你想要什么有很多可能的解决方案。我建议您为此创建一个存储过程。例子

DELIMITER $$
CREATE PROCEDURE InsertOrUpdate
BEGIN
    DECLARE `result` int;
    SET `result` := (   
                        SELECT COUNT(*) 
                        FROM database
                        WHERE action = 'eat' AND
                             `user` = 'me'
                    );
    IF  `result` > 0 THEN
        UPDATE database 
        SET action = 'digest' 
        WHERE user = 'me';
    ELSE
        INSERT INTO database (user,action) 
        VALUES ('me','eat');
    END IF;
END $$
DELIMITER ;

用法,

call InsertOrUpdate();
于 2012-09-10T01:30:30.570 回答