简体   繁体   中英

How to Update a record if it exists otherwise insert a new record in MySQL

I am trying to write a MySQL query to update a record if it exists otherwise create a new record into 2 different tables. I found some information online but i can't seems to nail it.

This is my current query

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

I am running into a syntax error

#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 

Can someone please help me with this error?

Note: if multiple records exists I should update all of them but if no record exist them insert only 1 record in each table.

Thanks

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM