从2个表中删除
我的数据库
用户中有 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
当然,如果
interests
表是InnoDB &对具有ON DELETE CASCADE
的用户有外键约束,当用户被删除时,这将自动完成。Of course, if the
interests
table was InnoDB & had a foreign key constraint to users with anON DELETE CASCADE
this would be done automatically when a user gets deleted.如果您使用的是 InnoDB,则可以为引用
users.ID
并具有ON DELETE CASCADE
的interests (User_ID)
定义外键约束>。然后,您只需从users
中删除该行,interests
中引用该用户的所有行都会自动删除。如果您不使用 InnoDB,那么 Wrikken 的解决方案可以正常工作。
If you're using InnoDB, then you can define a foreign key constraint for
interests (User_ID)
that referencesusers.ID
and hasON DELETE CASCADE
. Then you just have to delete the row fromusers
and all the rows ininterests
that reference that user will automatically be deleted.If you're not using InnoDB, then Wrikken's solution works fine.