0

I am trying to delete a post I have created, but that post could also have likes or comments.

So obviously I want to be able to delete those comments or likes if I try to delete the post!

Now I have some code which is kind of working.

This code:

DELETE p, a, n
            FROM Posts p
            INNER JOIN Activity a ON a.uuidPost = p.uuid
            LEFT OUTER JOIN Notifications n ON n.uuidPost = p.uuid
            WHERE p.uuid = '$uuid'

Deletes the post, but only if there is some activity(for ex. likes or comments), but if there are no likes or comments It does not delete the post...

I could do with some help trying to understand why this is happening if possible?!

Many thanks in advance to anyone that can spare some time for me!

2
  • INNER JOIN only finds rows if they match in both tables. That's the difference between INNER JOIN and OUTER JOIN. Commented Jan 13, 2017 at 16:41
  • @Barmar Hello, so what would you recommend? I just change the 'INNER JOIN' to 'OUTER JOIN' and it worked... Would that be correct? Commented Jan 13, 2017 at 16:46

1 Answer 1

1

When you use INNER JOIN, it only returns rows that have matches between the two tables, and DELETE only deletes rows that are returned by the JOIN. If you want to delete posts even if they have nothing matching in Activity, you should use LEFT OUTER JOIN -- this will return rows from the first table even if they have no matches.

DELETE p, a, n
FROM Posts p
LEFT OUTER JOIN Activity a ON a.uuidPost = p.uuid
LEFT OUTER JOIN Notifications n ON n.uuidPost = p.uuid
WHERE p.uuid = '$uuid'

BTW, if you declare uuidPost as foreign keys with ON DELETE CASCADE, you don't need to use the joins at all -- the CASCADE option automatically deletes the related rows in those tables when you delete the post.

Sign up to request clarification or add additional context in comments.

1 Comment

Fantastic! Thanks a lot, your second option sounds interesting...Would you recommend changing my current query? or would they work exactly the same?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.