Mysql: Insert with conditional

Asked

Viewed 345 times

1

I need to realize the following situation below, but when executing I have the error:

/* SQL 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 'INTO produto_seriais(serial_id) VALUES( SELECT id FROM serials WHERE serial =' at line 5 */

SELECT CASE WHEN (
    SELECT COUNT(id) FROM seriais WHERE serial = '2020'
) > 1
THEN
    (INSERT INTO produto_seriais(serial_id) VALUES(
        SELECT id FROM seriais WHERE serial = '2020'
    ))
ELSE (
    INSERT INTO seriais (serial) VALUE('2020');
    SET @last_id_in_table1 = LAST_INSERT_ID();
    INSERT INTO produto_seriais (serial_id) VALUES (@last_id_in_table1);
)
END;

The case is as follows:

I will search in the table "serials" by the serial "X". If it already exists, save your ID in the table "product_serials". If it does not exist (the serial), I will save it, retrieve your ID and save it in "product_serials". Any suggestions on how to do this?

Important note: this routine will run thousands of times at each run (10,000 or more depending on the number of serials).

  • enter a space between serials and (serial_id): produto_seriais (serial_id)

No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.