如何删除具有递归结构的表(MySQL)的所有行?

发布于 2024-10-08 17:17:52 字数 189 浏览 3 评论 0原文

我的数据库中有一个表,其中每一行都有一个父 id,它是表中另一行的 id(该表表示树状结构)。我想清空桌子。但是当我执行时

DELETE FROM table_name WHERE true;

出现错误(外键约束)。我该如何清空桌子呢?

澄清:我想删除整个表的内容,而不是表本身。

I have a table in my DB, in which every row has a parent id which is the id of another row in the table (the table represents a tree-like structure). I would like to empty the table. But when I perform

DELETE FROM table_name WHERE true;

I get an error (foreign key constraint). How do I empty the table anyway?

Clarification: I want to delete the whole table's contents, not the tables themselves.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

人事已非 2024-10-15 17:17:52

创建外键关系时,您需要指定on删除级联

编辑:这里有一个很好的参考:http://en.wikipedia.org/wiki/Foreign_key

When you create your foreign key relationships, you need to specify on delete cascade.

EDIT: There's a pretty good reference right here: http://en.wikipedia.org/wiki/Foreign_key

屋檐 2024-10-15 17:17:52

这应该可以解决问题:

TRUNCATE table_name;

This should do the trick:

TRUNCATE table_name;
老娘不死你永远是小三 2024-10-15 17:17:52

如果您无法更改 ON DELETE 行为,您可以重复执行此操作,直到表为空:

DELETE FROM table_name WHERE id NOT IN (SELECT parent_id FROM table_name)

If you can't change the ON DELETE behavior, you can do this repeatedly until the table is empty:

DELETE FROM table_name WHERE id NOT IN (SELECT parent_id FROM table_name)
反差帅 2024-10-15 17:17:52

首先删除没有子项的行。

因此,如果 id 外键是parent_id,请执行以下操作:

DELETE FROM table_name WHERE parent_id IS NOT NULL;

然后删除其余部分:

DELETE FROM table_name;

First delete the rows that have no children.

So if the id foreign key is parent_id, do something like:

DELETE FROM table_name WHERE parent_id IS NOT NULL;

Then delete the rest:

DELETE FROM table_name;
时常饿 2024-10-15 17:17:52

一个旧线程,但我会发布我的答案只是为了帮助任何人阅读这个问题。

我遇到了同样的问题,最终在执行删除语句之前将父列设置为 null。

UPDATE table_name SET parent_id=null WHERE true;

DELETE FROM table_name WHERE true;

An old thread but I'll post my answer just to help anyone reading this question.

I had the same issue and I ended up setting the parent column to null before executing the delete statement.

UPDATE table_name SET parent_id=null WHERE true;

DELETE FROM table_name WHERE true;
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文