[英]delete parent automatically if child was deleted
This my database relationship. 这是我的数据库关系。
I got data like this: 我得到这样的数据:
LikeDislike
|-------------|--------------|-----------------|
| id | userId | createdAt |
|-------------|--------------|-----------------|
| 1 | 1 | 2019-03-26 |
|-------------|--------------|-----------------|
RoomLikes
|------------------|--------------|
| likeDislikeId | roomId |
|------------------|--------------|
| 1 | 1 |
|------------------|--------------|
I want to do: 我想要做:
RoomLikes
, like DELETE FROM roomlikes where id = 1
当我从RoomLikes
删除数据时,例如DELETE FROM roomlikes where id = 1
LikeDislike
that related with RoomLikes
will be deleted automatically. 在数据LikeDislike
与相关RoomLikes
将被自动删除。 Is there are ways to delete data of parent automatically if data of child was deleted? 如果删除了孩子的数据,有自动删除父母的数据的方法吗?
Please let me know if you need more info. 如果您需要更多信息,请告诉我。
Thanks. 谢谢。
If I understand the question you need to look into using a join in your delete statement - something like this: 如果我理解这个问题,则需要研究在delete语句中使用联接-像这样:
DELETE RoomLikes, LikeDislike
FROM RoomLikes
INNER JOIN LikeDislike ON RoomLikes.likeDislikeId = LikeDislike.id
WHERE roomlikes.id=1;
You can use following queries 您可以使用以下查询
ALTER TABLE RoomLikes add foreign key (likeDislikeId) references LikeDislike(id) ON DELETE CASCADE; ALTER TABLE RoomLikes在DELETE CASCADE上添加外键(likeDislikeId)引用LikeDislike(id);
Just remember that you need to have primary key in the referenced table (LikeDislike) to add foreign key. 只需记住,您需要在引用表中拥有主键(LikeDislike)才能添加外键。 By using this, if you delete data on parent table, data of child table will be deleted. 通过使用此方法,如果删除父表上的数据,则子表的数据将被删除。
Is it correct that a record in LikeDislike
has exactly 1 child record that is either a RoomLike
or a CommentLike
? LikeDislike
中的记录是否只有1个子记录,即RoomLike
或CommentLike
是否正确?
In that case you might consider altering the corresponding foreign keys with ON DELETE CASCADE
and most of all, deleting the parent record instead of the child record. 在这种情况下,您可以考虑使用ON DELETE CASCADE
更改相应的外键,最重要的是,删除父记录而不是子记录。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.