gpt4 book ai didi

mysql - 如果删除了子项,则自动删除父项

转载 作者:太空宇宙 更新时间:2023-11-03 11:24:43 26 4
gpt4 key购买 nike

这是我的数据库关系。

enter image description here

我得到这样的数据:

LikeDislike
|-------------|--------------|-----------------|
| id | userId | createdAt |
|-------------|--------------|-----------------|
| 1 | 1 | 2019-03-26 |
|-------------|--------------|-----------------|

RoomLikes
|------------------|--------------|
| likeDislikeId | roomId |
|------------------|--------------|
| 1 | 1 |
|------------------|--------------|

我想做的事:

  1. 当我从 RoomLikes 中删除数据时,例如 DELETE FROM roomlikes where id = 1
  2. LikeDislike 中与RoomLikes 相关的数据将被自动删除。

如果删除了 child 的数据,有没有办法自动删除 parent 的数据?

如果您需要更多信息,请告诉我。

谢谢。

最佳答案

您可以使用以下查询

ALTER TABLE RoomLikes 添加外键 (likeDislikeId) 引用 LikeDislike(id) ON DELETE CASCADE;

请记住,您需要在引用表 (LikeDislike) 中有主键才能添加外键。使用这个,如果删除父表的数据,子表的数据也会被删除。

关于mysql - 如果删除了子项,则自动删除父项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55413263/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com