0

我正在尝试编写一个 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 条记录。

谢谢

4

1 回答 1

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
于 2013-07-21T19:58:32.867 回答