MySQL - Trigger to update Column in another table after insert where it satisfys other values(MySQL - 在插入满足其他值的位置后触发更新另一个表中的列)
问题描述
第一次发帖,请多多包涵:
First time posting, so bear with me:
我有 3 个表:CWUsers、CWGamesList 和 CWOwnsGame.
I have got 3 tables: CWUsers, CWGamesList and CWOwnsGame.
CWUsers 包含用户名和他们通过购买的游戏获得的当前忠诚度积分.
CWUsers contains a users name and current loyalty points they have earned through games they have bought.
CWGamesList 包含游戏名称、游戏机类型以及用户在购买游戏时将获得的忠诚度积分.
CWGamesList contains the name of the game, the console type and the loyalty points that the user will receive when purchasing game.
CWOwnsGame 是一个事务表,其中记录了用户名、游戏名称和控制台类型.
CWOwnsGame is a transactions table, where it records the users name, the name of the game and the console type.
购买游戏后使用忠诚度积分更新 CWUsers 表时遇到问题.
Been having problems updating the CWUsers table with loyaltypoints after purchasing a game.
原来我在像这样插入 CWOwnsGame 后有一个触发器:
Originally I had a trigger after inserting into CWOwnsGame like this:
UPDATE CWUSERS SET loyaltyPoints = loyaltyPoints +
(SELECT loyaltyPoints FROM CWGameList WHERE gameConsole = "Wii" AND gameName = "Mario")
WHERE username = "bob"
虽然这仅适用于一个实例,但您如何使其适用于任何购买的游戏.
Although this only works for one instance, how would you make it work for any game that is purchased.
谢谢
推荐答案
在 row
触发器中,您可以访问正在修改的行的两个版本:OLD
包含 曾经 的行(如果存在),NEW
包含该行因为它将是(如果它将存在.)
In a row
trigger you have access to two versions of the row being modified: OLD
contains the row as it was (if it existed), and NEW
contains the row as it will be (if it will exist.)
为了使您的触发器按您描述的那样工作,您将使用 NEW
中的值来调节 WHERE
子句,就像这样:
To make your trigger work as you described, you would condition the WHERE
clause using values from NEW
, like so:
CREATE TRIGGER update_loyalty_points
AFTER INSERT ON CWUserOwnsGame
FOR EACH ROW
UPDATE CWUsers
SET loyaltyPoints = loyaltyPoints +
(SELECT loyaltyPoints
FROM CWGameList
WHERE gameConsole = NEW.cName
AND gameName = NEW.gName)
WHERE username = NEW.uName;
我假设您已在表之间一致地命名列.请注意,NEW
中的正确列与 CWOwnsGame
中的列具有相同的名称.
I've assumed that you've named your columns consistently between tables. Note that the correct columns in NEW
have the same names as the columns in CWOwnsGame
.
这篇关于MySQL - 在插入满足其他值的位置后触发更新另一个表中的列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:MySQL - 在插入满足其他值的位置后触发更新另一个表中的列
基础教程推荐
- 无法在 ubuntu 中启动 mysql 服务器 2021-01-01
- ERROR 2006 (HY000): MySQL 服务器已经消失 2021-01-01
- 使用pyodbc“不安全"的Python多处理和数据库访问? 2022-01-01
- 如何在 SQL Server 的嵌套过程中处理事务? 2021-01-01
- SQL Server 中单行 MERGE/upsert 的语法 2021-01-01
- Sql Server 字符串到日期的转换 2021-01-01
- 在 VB.NET 中更新 SQL Server DateTime 列 2021-01-01
- SQL Server 2016更改对象所有者 2022-01-01
- 将数据从 MS SQL 迁移到 PostgreSQL? 2022-01-01
- SQL Server:只有 GROUP BY 中的最后一个条目 2021-01-01