When you exclude data from the first table, modify the value of the related field in the second table

Source: Internet
Author: User
When you delete data from the first table, modify the value of the related field in the second table
Table XF
XF_ID VIP Total
1 1 10
2 1 100
3 2 80
4 3 50


Table VIP
VIP Jifen
1 1000
2 500
3 800

$sql = "Delete from". $fdyu->table (' XF ').
"WHERE xf_id". Db_create_in (Join (', ', $_post[' checkboxes ')). If $_post[' checkboxes ' is xf_id:1,2,3,4
"and school_id=". $school _id;
$db->query ($sql);

So while deleting xf_id, the table VIP
1 jifen=1000-110=890 If the XF has more than one VIP, subtract the sum, such as the XF table VIP 1 has two data, their total and is 110,
Then minus 110.
2 jifen=500-80=420
3 jifen=800-50=750
That is, while deleting the data from the table XF, the Jifen in the table VIP will subtract the total from the XF
------Solution--------------------
Approximate idea

1. First get the VIP to delete the record, and the total score of each VIP deleted
Select Vip,sum (total) from the XF where xf_id in (1,2,3,4) group by VIP;
Save As Array
VIP is key
Total is value

$arr = Array (
' 1 ' = 110,
' 2 ' = 80,
' 3 ' = 50
);

2. Delete the records for the corresponding xf_id
Delete from the XF where xf_id in (1,2,3,4);

3. Modify the VIP Table
foreach ($arr as $vip = = $total) {
Update VIP set jifen=jifen-$total where vip= $VIP
}

------Solution--------------------
You can consider using a trigger, in MySQL execution, to give you an example:

Create trigger delete_jifen before delete on jifen
For each row
BEGIN
UPDATE Users
(SELECT sum (jifen.jifen) from Jifen where Jid = Old.jid) where Users.userid = Old.userid;
END
  • 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.