使用触发器在 MySQL 中的表上伪造自动增量增量
我的 MySQL 数据库中有一个内容表(Drupal 内容表,就其价值而言),它有一个自动递增的主键 nid。我希望能够实现奇数和偶数 id 解决方案,其中在生产中创建的内容具有偶数 id,而在开发中创建的内容具有奇数 id,以避免同步时出现 id 冲突。不幸的是,MySQL 不支持序列或每表自动增量增量值(即仅对 db.node 增量 2,而不是 1)。
我能想到的最好的解决方案是有一个 BEFORE INSERT 和 AFTER INSERT 触发器,它在 BEFORE INSERT 触发器中将 auto_increment_increment 的会话值设置为 2,然后在 AFTER INSERT 触发器中将其重置为 1。因为它只设置会话变量,所以它不应该对其他进程产生任何影响,而且由于它是一个 Drupal CMS 表并且没有发生任何复杂的事情,所以它看起来很安全,尽管感觉不对。
然而,我是一名中级 MySQL 管理员(充其量是:)),正如我所说,这确实感觉很黑客,所以我想我应该把它放在那里,看看是否有人对此有任何强烈的负面反应,也许是我的一些问题我没有预见到。 (我想如果没有人这样做,那么也许其他人会发现这很有用)。
I have a content table in my MySQL database (a Drupal content table, for what it's worth), which has an auto incremented primary key, nid. I want to be able to implement an odd and even id solution, where content created on production has even ids and content created on dev has odd ids, to avoid id conflicts when I sync. Unfortunately, MySQL doesn't support sequences, or per-table auto increment increment values (i.e. increment by 2 only for db.node, rather than 1).
The best solution I can think of, is to have a BEFORE INSERT and AFTER INSERT trigger which sets the session value of auto_increment_increment to 2 in the BEFORE INSERT trigger, and then resets it to 1 in the AFTER INSERT trigger. Since it only sets the session variable, it shouldn't have any effect on other processes, and since it's a Drupal CMS table and nothing complicated is happening, it seems safe, even though it feels wrong.
However, I'm an intermediate MySQL Admin (at best :) ) and as I said it certainly feels hackish, so I thought I'd put this out there and see if anyone has any strong negative reactions to this, perhaps some issue I'm not foreseeing. ( And I suppose if no one does then maybe someone else will find this useful).
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这是您想要执行的操作的一个简单示例 - 假设有一个整数列“seq”
在“my_table_name”表中:
Here's a simple example of what you want to do - assuming there is an integer column 'seq'
in the 'my_table_name' table: