0

This my database relationship.

enter image description here

I got data like this:

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

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

I want to do:

  1. When I delete a data from RoomLikes, like DELETE FROM roomlikes where id = 1
  2. The data in LikeDislike that related with RoomLikes will be deleted automatically.

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.

JillAndMe
  • 3,989
  • 4
  • 30
  • 57
  • 5
    This is what you need : [ON DELETE CASCADE OR TRIGGER](https://stackoverflow.com/a/21301567/2794280) – kgzdev Mar 29 '19 at 08:32
  • What about the `CommentLikes`? They appear to have a foreign key towards `LikeDislike` Aren't you afraid records become orphan when deleting an element from `LikeDislike`? – Robert Kock Mar 29 '19 at 08:46
  • @ikram maybe I'm missing something but ON DELETE CASCADE deletes child records automatically when deleting a parent record. Not the other way around – Robert Kock Mar 29 '19 at 08:49
  • A parent can have only 1 child? – P.Salmon Mar 29 '19 at 08:51
  • @RobertKock yes, correct. In this case OP can use Trigger – kgzdev Mar 29 '19 at 09:01

3 Answers3

1

If I understand the question you need to look into using a join in your delete statement - something like this:

DELETE RoomLikes, LikeDislike
FROM RoomLikes
INNER JOIN LikeDislike ON RoomLikes.likeDislikeId = LikeDislike.id
WHERE roomlikes.id=1;
bhttoan
  • 2,641
  • 5
  • 42
  • 71
1

You can use following queries

ALTER TABLE RoomLikes add foreign key (likeDislikeId) references LikeDislike(id) ON DELETE CASCADE;

Just remember that you need to have primary key in the referenced table (LikeDislike) to add foreign key. By using this, if you delete data on parent table, data of child table will be deleted.

Alina
  • 56
  • 6
  • You said when I delete a data on parent table then, data of child table will be deleted, then Is the opposite way possible? I mean when I delete data of child table then, data on parent will be deleted. – JillAndMe Mar 29 '19 at 11:36
  • It is not possible using just foreign key but if you want do that maybe you can use stored procedures or triggers – Alina Apr 01 '19 at 03:42
1

Is it correct that a record in LikeDislike has exactly 1 child record that is either a RoomLike or a 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.

Robert Kock
  • 5,795
  • 1
  • 12
  • 20