从2个表中删除

发布于 2024-11-24 18:39:37 字数 656 浏览 1 评论 0原文

我的数据库

用户中有 2 个表...

ID    Username    Randomkey
1     Dionne      938493
2     Liam        902303
3     James       232039
4     Sarah       320923

兴趣...

ID    User_ID    Interest
1     3          Army
2     3          Boxing
3     3          Tennis
4     4          Make Up

在我的兴趣表中,“User_ID”等于我的用户表中的“ID”。

我想编写一个查询,当触发时,从我的“用户”表中删除该行,同时从兴趣表中删除与用户相关的所有数据。

我不确定如何做到这一点,而且我在谷歌上也没有运气。

如果有人能给我一些建议,或者至少指出我在哪里可以找到这些信息,那将是一个很大的帮助。

在我的脑海里,我认为这会是这样的:

DELETE FROM users, interests WHERE ID = '$userID' AND User_ID = '$userID'

I have 2 tables in my DB

users...

ID    Username    Randomkey
1     Dionne      938493
2     Liam        902303
3     James       232039
4     Sarah       320923

interests...

ID    User_ID    Interest
1     3          Army
2     3          Boxing
3     3          Tennis
4     4          Make Up

In my interests table, 'User_ID' is equal to 'ID' from my users table.

I want to write a query that when triggered, deletes the row from my 'users' table and at the same time deletes all data relating to the user from the interests table.

I'm unsure how to do this and I've had no luck with Google.

If anybody could give me some advice or at least point me where to find this information it would be a great help.

In my head I'm thinking it would be something along the lines of:

DELETE FROM users, interests WHERE ID = '$userID' AND User_ID = '$userID'

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

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

发布评论

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

评论(2

夕嗳→ 2024-12-01 18:39:37
DELETE users, interests 
FROM users 
LEFT JOIN interests ON users.ID = interests.User_ID
WHERE users.ID = <id>;

当然,如果interests表是InnoDB &对具有 ON DELETE CASCADE 的用户有外键约束,当用户被删除时,这将自动完成。

DELETE users, interests 
FROM users 
LEFT JOIN interests ON users.ID = interests.User_ID
WHERE users.ID = <id>;

Of course, if the interests table was InnoDB & had a foreign key constraint to users with an ON DELETE CASCADE this would be done automatically when a user gets deleted.

风吹短裙飘 2024-12-01 18:39:37

如果您使用的是 InnoDB,则可以为引用 users.ID 并具有 ON DELETE CASCADEinterests (User_ID) 定义外键约束>。然后,您只需从 users 中删除该行,interests 中引用该用户的所有行都会自动删除。

如果您不使用 InnoDB,那么 Wrikken 的解决方案可以正常工作。

If you're using InnoDB, then you can define a foreign key constraint for interests (User_ID) that references users.ID and has ON DELETE CASCADE. Then you just have to delete the row from users and all the rows in interests that reference that user will automatically be deleted.

If you're not using InnoDB, then Wrikken's solution works fine.

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