How do I truncate tables properly?

 ̄綄美尐妖づ 提交于 2019-11-28 17:03:09

问题


I'm using datamapper with ruby to store data to certain tables.

Several of the tables have very large amounts of information and I want to clear them out when the user 'rebuilds database' (it basically deletes everything and re-calculates data).

I originally tried Forum.all.destroy and did it for all the different tables, but I noticed some of them just werent deleted from within phpmyadmin. i can only imagine its because of foreign keys. Although I really dont know because my other table which foreing keys was successfully deleted. Not to mention, id rather just 'zero' it out anyway so the keys dont get to extraordinarly large numbers (like key #500,000).

I then tried running it with the code below, but it doesnt clear the tables out because of 'foreign key constraints'. I want to force it to work because I know for a fact I'm clearing out all the tables that rely on each other (i'm only not clearing out 2 tables, a settings table and a random storage table, neither of which use foreign keys).

So far I have...

adapter = DataMapper.repository(:default).adapter
adapter.execute('TRUNCATE TABLE `forums`, `dates`, `remarks`');

That would be fine except the mysql syntax is wrong apparently. so thats the first thing

I did it 1 by 1 in phpmyadmin and when i did it that way it says

Cannot truncate a table referenced in a foreign key constraint

回答1:


Plan A:

SET FOREIGN_KEY_CHECKS = 0; -- Disable foreign key checking.
TRUNCATE TABLE forums;
TRUNCATE TABLE dates;
TRUNCATE TABLE remarks;
SET FOREIGN_KEY_CHECKS = 1; -- Enable foreign key checking.

Plan B:

You should truncate child tables firstly, then parent tables.

Disabling foreign key checks risks entering rows into your tables that don't adhere to the constraints which can cause undefined behavior.




回答2:


Instead of using Disable foreign key checking.

You can use the below code.

DELETE FROM forums;
ALTER TABLE forums AUTO_INCREMENT = 1;

DELETE FROM dates;
ALTER TABLE dates AUTO_INCREMENT = 1;

DELETE FROM remarks;
ALTER TABLE remarks AUTO_INCREMENT = 1;

It will just delete all the rows and make id increment from 1 onwards.



来源:https://stackoverflow.com/questions/8641703/how-do-i-truncate-tables-properly

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!