HiveBrain v1.2.0
Get Started
← Back to all entries
patternsqlMinor

Optimizing my update sequence

Submitted by: @import:stackexchange-dba··
0
Viewed 0 times
optimizingsequenceupdate

Problem

Whenever a user updates his profile, we conduct a set of queries like so:

DELETE FROM `user_likes` WHERE `ID` = $id
INSERT INTO `user_likes` VALUES (DEFAULT, $id, $interest_id, $interest_name)


Is there a way to do this all in one step? There has to be a way, because the interest IDs are all different for each user. Keep in mind that the data never actually has to be deleted - it's a set that is always growing.

Solution

If you just updating the interest id and name, use UPDATE

UPDATE user_likes SET
`interest_id` = $interest_id,
`interest_name` = '$interest_name'
WHERE `ID` = $id;


If you want to mechanically do a DELETE followed by an UPDATE, use REPLACE

REPLACE INTO `user_likes` VALUES (DEFAULT, $id, $interest_id, $interest_name);


Please test these out on a Dev DB Server to make sure this is what you want

Code Snippets

UPDATE user_likes SET
`interest_id` = $interest_id,
`interest_name` = '$interest_name'
WHERE `ID` = $id;
REPLACE INTO `user_likes` VALUES (DEFAULT, $id, $interest_id, $interest_name);

Context

StackExchange Database Administrators Q#22697, answer score: 6

Revisions (0)

No revisions yet.