使用当前的 auto_increment 值作为同一 INSERT 查询中另一个字段的基础 - 这在 MySQL 中可能吗?
在我的表(MySQL)中,我有以下字段:
id
- 主要,自动增量
hash
-
我想填充的 id
的 Base 36 表示同时使用存储过程计算 INSERT 上收到的 id 值的以 36 为基数的等效值。 像这样的事情:
INSERT into `urls` (`id`,`hash`) VALUES (NULL,base36(`id`));
显然这不起作用,但我希望它能说明我想要实现的目标。 这可能吗?如果可能的话,如何实现?
注意:我只想使用一个查询,因此 last_insert_id 没有帮助(至少据我所知)。
In my table (MySQL) I have these fields:
id
- primary, auto_increment
hash
- base 36 representation of id
I'd like to populate both fields at once, using a stored procedure to compute the base 36 equivalent of the value id receives on INSERT. Something like this:
INSERT into `urls` (`id`,`hash`) VALUES (NULL,base36(`id`));
Obviously this doesn't work, but I hope it illustrates what I'm trying to achieve. Is this possible, and if so, how?
Note: I want to use only one query, so last_insert_id isn't helpful (at least as I understand).
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这个问题本质上是对这个的重述其他一个。 简而言之,自动增量字段的优点是保证值是唯一的,缺点是在执行 INSERT 之前该值不存在。
情况确实如此。必然。 例如,您可以检索给定表的下一个自动增量值是什么,但由于并发问题,您无法确定您下一个执行的查询将是得到那个ID。 别人可能会先拿走。 因此,ID 字段的分配必须是在插入记录时发生的原子获取和递增操作。
换句话说,尽管您可能想要在单个查询中执行此操作,但您根本不会这样做。 从理论上讲,您可以通过在 INSERT 上附加一个触发器来假装您只执行一个查询,该触发器会在事后添加 ID 字段的替代表示形式。 或者,您可以使用基于提前已知信息的非自动增量 ID 字段。
This question is essentially a restatement of this other one. In a nutshell, the advantage of an auto increment field is that the value is guaranteed unique, the disadvantage is that the value doesn't exist until the INSERT has already been executed.
This is necessarily the case. You can, for example, retrieve for a given table what the next auto increment value will be, but because of concurrency concerns, you can't be sure that the query you execute next will be the one that gets that ID. Someone else might take it first. The assignment of the ID field has to be, therefore, an atomic get-and-increment operation that happens as the record is being inserted.
In other words, though you may want to do this in a single query, you're simply not going to. There's a way you could theoretically pretend that you're only executing one query by attaching a trigger on INSERT that adds your alternate representation of the ID field after the fact. Alternately, you can use a non-auto-increment ID field based on something known ahead of time.
尽管您无法在单个查询中执行此操作,但您可以执行以下操作:
Although you can't do that in a single query, you can do this:
您可以使用触发器来执行此操作,例如:
You could do this using a trigger, something like: