E
E
evilelf2015-01-01 18:50:38
MySQL
evilelf, 2015-01-01 18:50:38

How less resource-intensive to implement an addition or update?

Given : Table with columns id, user_id, meta_key, meta_val
Task : There was a need to make a multiple addition of records to the table with user_id==3, but if there is a row with equal meta_key, then it needs to be updated.
Suggestion 1 : Do this in several queries (1st: take all non-empty rows by user_id, 2nd: update them if they have been replaced, 3rd: add new rows if necessary)
Suggestion 2 : Make a procedure in which to pass mutable values. In procedure to compare and there to solve update or insert.
Thank you.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
R
Rsa97, 2015-01-01
@evilelf

If user_id, meta_key is a unique pair (UNIQUE KEY(`user_id`, `meta_key`)), then

INSERT INTO `table` (`user_id`, `meta_key`, `meta_val`)
    VALUES (:user_id, :meta_key, :meta_val)
    ON DUPLICATE KEY UPDATE `meta_val` = VALUES(`meta_val`)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question