MySQL - UPDATE或INSERT(如果存在)

时间:2013-10-04 15:29:58

标签: mysql

我在MySQL数据库中有一个表,如果实例尚不存在则需要更新。我尝试了以下方法,但没有更接近解决方案:

SET @last_message_id = (
SELECT id FROM mailbox_last_message WHERE conversationId = '13'
);

BEGIN TRANSACTION;
UPDATE mailbox_last_message SET conversationId = '13', initiatorMessageId = '20', interlocutorMessageId = '10' 
WHERE id = @last_message_id 
IF (@@ROWCOUNT = 0)
INSERT INTO  mailbox_last_message (  id ,  conversationId ,  initiatorMessageId ,  interlocutorMessageId ) 
VALUES ('' , '13', '20', '0' );
COMMIT;

这一个:

 SET @last_message_id = (
 SELECT `id` FROM mailbox_last_message WHERE `conversationId` = 13);

 INSERT INTO  mailbox_last_message (  id ,  conversationId ,  initiatorMessageId ,  interlocutorMessageId ) 
 VALUES ( '', '13', '20', '0' ) ON DUPLICATE 
 KEY UPDATE id = @last_message_id

此解决方案使用conversationId 13创建一个新实例,这不是我想要的。我试图在线搜索文档和各种教程/示例,但我找不到任何合适的解决方案。任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:2)

如果您希望保持唯一的字段具有唯一索引,则可以使用INSERT IGNORE INTO语法

    SET @last_message_id = (
SELECT id FROM mailbox_last_message WHERE conversationId = '13'
);

    INSERT IGNORE INTO  mailbox_last_message (  id ,  conversationId ,  initiatorMessageId ,  interlocutorMessageId ) 
    VALUES ('' , '13', '20', '0' ) ON DUPLICATE KEY UPDATE id = @last_message_id;