简体   繁体   English

使用PHP / MySQL循环更新当前行

[英]Update Current Row Using PHP/MySQL Loop

I have a MySQL table with over 16 million rows and there is no primary key. 我有一个超过1600万行的MySQL表,没有主键。 Whenever I try to add one, my connection crashes. 每当我尝试添加一个时,我的连接就会崩溃。 I have tried adding one as an auto increment in PHPMyAdmin and in command line but the connection is always lost after about 10 minutes. 我尝试在PHPMyAdmin和命令行中添加一个作为自动增量,但是在大约10分钟后,连接始终会丢失。

What I would like to do is loop through the table's rows in PHP so I can limit the number of results and with each returned row add an auto-incremented ID number. 我想做的是在PHP中遍历表的行,这样我就可以限制结果的数量,并为每个返回的行添加一个自动递增的ID号。 Since the number of impacted rows would be reduced by reducing the load on the MySQL query, I won't lose my connection. 由于可以通过减少MySQL查询的负载来减少受影响的行数,因此我不会丢失连接。

I want to do something like 我想做类似的事情

SELECT * FROM MYTABLE LIMIT 1000001, 2000000;

Then, in the loop, update the current row 然后,在循环中,更新当前行

UPDATE (current row) SET ID='$i++'

How do I do this? 我该怎么做呢?

I am open to a MySQL solution as well. 我也对MySQL解决方案持开放态度。 I just need a process that will not cause me to lose my MySQL connection 我只需要一个不会导致我失去MySQL连接的过程

Note: the original data was given to me as a txt file. 注意:原始数据是作为txt文件提供给我的。 I don't know if there are duplicates but I cannot eliminate any rows. 我不知道是否存在重复项,但无法消除任何行。 Also, no rows will be added. 同样,将不添加任何行。 This table is going to be used only for querying purposes. 该表将仅用于查询目的。 When I have added indexes, however, there were no problems. 但是,当我添加索引后,就没有问题了。

It is easier 更容易

ALTER TABLE table_name MODIFY COLUMN id INT NOT NULL AUTO_INCREMENT PRIMARY KEY

In case you want to remove the primary key after the modification 如果您要在修改后删除主键

ALTER TABLE table_name MODIFY COLUMN id INT

I would avoid setting primary keys manually. 我会避免手动设置主键。 Much safer to let MySQL do it. 让MySQL做到这一点要安全得多。 You can temporarily increase the timeout in the config file: 您可以在配置文件中临时增加超时:

wait_timeout = 28800
interactive_timeout = 28800

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

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