且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

插入时连接字符串和主键 ID

更新时间:2023-02-04 14:44:17

如果 user_id 是一个 AUTO_INCREMENT 主键,那么你不能用一条语句做到这一点,即使你使用触发器.

If user_id is an AUTO_INCREMENT primary key, then you can't do this with a single statement, even if you use a trigger.

问题是在 BEFORE INSERT 触发器运行之后才会生成 AUTO_INCREMENT 值,但是您不能在 AFTER INSERT 中更改 username 触发器.

The problem is that the AUTO_INCREMENT value isn't generated until after the BEFORE INSERT trigger runs, but you can't change username in the AFTER INSERT trigger.

所以你只需要执行INSERT,然后立即执行UPDATE.

So you just have to do the INSERT, then immediately do an UPDATE.

如果 user_id 不是 AUTO_INCREMENT,而是您自己指定的东西,那么很简单,您只需在传递值之前在 PHP 代码中进行连接作为参数.

If user_id is not an AUTO_INCREMENT, but instead is something you specify yourself, then it's easy, you just do the concatenation in your PHP code before you pass the values as parameters.

更新:您也无法使用 MySQL 5.7 生成的列来执行此操作.当您尝试创建表时会导致此错误:

Update: You can't do it with MySQL 5.7 generated columns either. It results in this error when you try to create the table:

生成的列用户名"不能引用自增列.

Generated column 'username' cannot refer to auto-increment column.