简体   繁体   English

为MySQL中的所有新表随机设置AUTO_INCREMENT

[英]Setting AUTO_INCREMENT randomly for all new tables in MySQL

Is there a way to automatically set AUTO_INCREMENT to a random value whenever a new table is created in MySQL? 每当在MySQL中创建新表时,是否可以自动将AUTO_INCREMENT设置为随机值?

Some background: as a developer I regularly work with multiple local installs of Moodle. 背景知识:作为一名开发人员,我经常处理Moodle的多个本地安装。 A few times I have been caught out by subtle bugs in my SQL statements where I've mixed up the IDs from two different tables, but this has been masked by both tables having the same numerical value for their ID. 几次我都被我的SQL语句中的细微错误所困住了,在这些错误中,我混合了来自两个不同表的ID,但这被两个具有相同ID值的表所掩盖。 eg during development, a forum with ID 1 also has a post in it with ID 1, so an SQL statement which muddles-up forum.id and post.id will appear to work locally, but then start giving errors when deployed to the testing server. 例如,在开发过程中,ID为1的论坛中也有ID为1的帖子,因此混淆了forum.id和post.id的SQL语句似乎在本地工作,但是部署到测试时便开始出错服务器。

If AUTO_INCREMENT always had a random starting point, then such mistakes would be much more likely to be spotted immediately. 如果AUTO_INCREMENT始终有一个随机的起点,那么这种错误很可能立即被发现。

Note - for one Moodle install, it would be trivial to tweak the code to set a random AUTO_INCREMENT value whenever I created a new table. 注意-对于一次Moodle安装,每当我创建一个新表时,对代码进行调整以设置随机的AUTO_INCREMENT值将是微不足道的。 Unfortunately, I currently have 30-40 copies of the Moodle codebase for different clients, with new copies being added frequently, so a solution that worked automatically across all my local databases would be very helpful. 不幸的是,我目前为不同的客户提供30-40个Moodle代码库副本,并且经常添加新副本,因此自动在我所有本地数据库中工作的解决方案将非常有帮助。

You could use ALTER TABLE statement: 您可以使用ALTER TABLE语句:

ALTER TABLE your_table AUTO_INCREMENT = 13125;

Which you could probably script it with something like php: 您可能会用类似php的脚本编写脚本:

<?
  $q = "ALTER TABLE your_table AUTO_INCREMENT = ".rand(10000,99999);
?>

I dont know how much this suits your needs. 我不知道这多少适合您的需求。

Let me know what you think. 让我知道你的想法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM