dtbi27903 2018-11-23 18:12
浏览 97

当它已经在MySQL / PHP中构建时,防止创建索引

Currently I have an update-logic written in PHP which can update multiple tables inside a MySQL-database. Whenever a certain PHP-script is getting executed, the update-logic checks if the database is up-to-date (based on a version-flag which is saved somewhere else) and applies all necessary updates if not.

One part of the update-logic should add an index for a specific table-column:

if ($database_version < 1337) {
    if (!get_results("SHOW INDEX FROM my_table WHERE Key_name = 'my_key';")) {
        query("ALTER TABLE my_table ADD INDEX(my_key);");
    }

    set_database_version(1337);
}

As you can see I do the following setps:

  • Check if the database is below a specific version-flag
  • If so: Check if an index in table my_table for key my_key exists
  • If not: Create the index
  • Update the version-flag of the database

Now imagine that the update-logic is getting triggered by an user. Because the table is very big, the creation of the index can take a while. Before the creation of the index is done, another user triggers the update-logic. Because the index is not finished yet, the initial check returns FALSE and the update-logic starts another creation-query for this index - which means the index is getting built/created twice or even more often.

First I assumed that during the creation of an index a specific entry is made into a table before it is getting filled with values. But this seems to be not the case because the query

SHOW INDEX FROM my_table WHERE Key_name = 'my_key';

returns FALSE even when this index is just getting created.

My question: Is there a way to check via MySQL/PHP if an index exists OR is just getting created so I can prevent that it gets created multiple times?

  • 写回答

2条回答 默认 最新

  • dongshan4878 2018-11-23 19:10
    关注

    There is a way to see the index creation progress in MySql as described here: https://www.percona.com/blog/2014/02/26/monitor-alter-table-progress-innodb_file_per_table/.

    But I guess that would be too much to do when this can be achieved in a much simpler way.

    My suggestion would be to keep a lock variable set whenever a user is going to create the index. When the other user tries to execute the script the lock variable is checked if it's set or not and only when it's not set, the script goes forward to create the index.

    评论

报告相同问题?

悬赏问题

  • ¥20 搭建pt1000三线制高精度测温电路
  • ¥15 使用Jdk8自带的算法,和Jdk11自带的加密结果会一样吗,不一样的话有什么解决方案,Jdk不能升级的情况
  • ¥15 画两个图 python或R
  • ¥15 在线请求openmv与pixhawk 实现实时目标跟踪的具体通讯方法
  • ¥15 八路抢答器设计出现故障
  • ¥15 opencv 无法读取视频
  • ¥15 按键修改电子时钟,C51单片机
  • ¥60 Java中实现如何实现张量类,并用于图像处理(不运用其他科学计算库和图像处理库))
  • ¥20 5037端口被adb自己占了
  • ¥15 python:excel数据写入多个对应word文档