1

in the table 'chat':

enter image description here

I would like to delete messages if they have been deleted by both sender an recipient. If, however, a user is the first to delete a message, this should just be recorded under "deleted_by" with his user id (until the second user also deletes the message).

For message #3 and user #1 my query would look like so:

IF
    (SELECT deleted_by from chat WHERE id=3) <> '1' AND (SELECT deleted_by from chat WHERE id=3) <> '0' THEN
    DELETE FROM chat WHERE id=3
ELSE 
    UPDATE chat
    SET deleted_by=1
    WHERE id=3
END IF

This should delete message #3, but instead I get an error. Can you help me make my according SQLfiddle work?

Thank you!

1 Answer 1

1

A subquery isn't needed. Instead, you can just delete the row if the other user has already marked it deleted and if it still exists, mark it deleted:

DELETE FROM chat WHERE id = 3 AND deleted_by <> 0;
UPDATE chat SET deleted_by = 4 WHERE id = 3;
Sign up to request clarification or add additional context in comments.

2 Comments

Right, thank you! Just for curiosity, though: how could the same result be achived with if...else?
I think you'd have to use a compound statement for that. I haven't done anything with MySQL for a while, so I can't come up with a working example right now. Anyway, see dev.mysql.com/doc/refman/5.7/en/…

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.