MySQL batch Insert application ON DUPLICATE KEY UPDATE

Source: Internet
Author: User

MySQL batch Insert application ON DUPLICATE KEY UPDATE

It is not clear whether the problem is design or implementation.
At last, it was a strange demand for me.

Award_credit_room table, which stores user gift history
Award_credit is the point record generated by user gift giving.

After the data of award_credit_room is summarized, You need to Insert the data to the award_credit table in batches,
If no record exists, Insert the statement. If a record exists, Update the statement.

Use MySQL custom variables to implement insert... select... ON DUPLICATE KEY UPDATE

This function uses the following SQL

Set @ a: = 0;
Set @ B: = 0;
Insert into award_credit (credits, vvid, CreditsTotal)
Select @ a: = sum (CreditChange), VVID, sum (CreditChange)
From award_credit_room r
Where awardActId = 23 and Status = 2 group by VVID
On duplicate key update credits = credits + @ a, creditsTotal = creditsTotal + @;

Summary query results before execution
Select @ a: = sum (CreditChange), VVID, sum (CreditChange)
From award_credit_room r
Where awardActId = 23 and Status = 2 group by VVID


Award_credit table data before SQL Execution


Award_credit table data after SQL Execution

 

During the experiment, there was an optimization idea. Since both fields are sum aggregation, can we use custom variables to calculate them once,
In fact, the execution sequence and position of custom variables are not strictly fixed.


However, there are also workarounds.
Set @ a: = 0;
Insert into award_credit (credits, vvid, CreditsTotal)
Select @ a: = s, vvid, s from
(
Select sum (CreditChange) s, VVID from award_credit_room r where awardActId = 23 and Status = 2 group by VVID
) T1
On duplicate key update credits = credits + @ a, creditsTotal = creditsTotal + @;

This article permanently updates the link address:

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.