如果存在,则如何更新记录,否则在MySQL中插入新记录

时间:2013-07-21 19:49:14

标签: mysql sql-update mysql-insert-id

我正在尝试编写MySQL查询以更新记录(如果存在),否则在2个不同的表中创建新记录。我在网上找到了一些信息,但我似乎无法确定它。

这是我当前的查询

Set @time_now := NOW();

    if exists(SELECT 1 FROM phone_calls WHERE account_id = 8 AND call_code_id = 5 AND status = 1)
      BEGIN
        UPDATE phone_calls
        SET trigger_on=@time_now,
        isAppointment=1,
        modified_by = 2,
        modified_on = @time_now
        WHERE account_id =8 AND call_code_id = 5 AND status = 1;
       END
    ELSE
      BEGIN
        INSERT INTO phone_calls (mid_id, account_id, call_code_id, trigger_on, created_on, call_subject, status, next_call_id
                                , call_direction, owner_id, workflow_generated, call_notes, total_attempts, isAppointment)
                                VALUES (1, 8, 5, @time_now, @time_now, 'This is a test', 1, 0 , "OUTBOUND", 2, 1, "", 0, 0);
        INSERT INTO inventory_engine_history(phone_call_id, new_phone_call_id, created_by, new_call_owner, action, trigger_on) 
                                                VALUES(1000, LAST_INSERT_ID(), 2, 2, '', @time_now)';
       END

我遇到了语法错误

#1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'if exists(SELECT 1 FROM phone_calls WHERE account_id = 8 AND call_code_id = 5 AN' at line 1 

有人可以帮我解决这个错误吗?

注意:如果存在多个记录,我应该更新所有记录,但如果不存在记录,则每个表中只插入1条记录。

由于

1 个答案:

答案 0 :(得分:0)

DECLARE theCount INT;
SELECT COUNT(*) INTO theCount FROM phone_calls WHERE account_id = 8 AND call_code_id = 5 AND status = 1
IF(theCount=0) THEN -- DoLogic;
ELSE -- DoSomeOtherLogic;
END IF
相关问题