MySQL 触发器问题

标签 mysql triggers insert automation foreign-keys

因此,我尝试设置一个触发器,当我的用户表创建新行时,我的配置文件表中也会创建一个新行,并且用户表中的主键将插入到概况表。这是我目前正在使用的代码,但尚未成功。

    CREATE TRIGGER userID
AFTER INSERT ON user FOR EACH ROW
BEGIN
    INSERT INTO profile (userID)
    VALUES(user.userID);
END

配置文件表上的外键和用户表上的主键都称为 userID

最佳答案

user.userID在该上下文中并不意味着任何有用的东西,您想使用NEW引用新创建的行:

CREATE TRIGGER userID
AFTER INSERT ON user FOR EACH ROW
BEGIN
    INSERT INTO profile (userID)
    VALUES(NEW.userID);
END

来自fine manual :

You can refer to columns in the subject table (the table associated with the trigger) by using the aliases OLD and NEW. [...] NEW.col_name refers to the column of a new row to be inserted or an existing row after it is updated.

关于MySQL 触发器问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6811494/

相关文章:

mysql - 将数据从一个表更新到另一个表

mysql - 如何使用TRIGGER在MYSQL中自动更新表

sql - 使用 SQL Server Management Studio 添加新行?

mysql - 将数据库字段增加 1

MySQL 在 Sphinx 过滤器查询中将字符串转换为整数

php - 条件运算符未按预期执行

php - 如何获取登录用户的用户名

javascript - Jquery OnLoad - 奇怪的行为

mysql - 在不同的表上删除后删除一行?

mysql - 向mysql中插入数据