I have the following table for personal messages:
id* sender* recipient* del_by_rec del_by_send
-+----------+-------------+-----------+-----------+
2 tom beth 0 1
5 tom josh 0 1
5 tom chris 1 1
7 ashley burt 1 0
8 jenna tom 1 0
8 jenna ashley 0 0
8 jenna jenna 1 0
10 ashley burt 0 0
where
idis the message id,senderandrecipientare user logins,senderis unique to a messageid- there can be more than one
recipientto a messageid del_by_recis 1 if message has been deleted by recipient from his inbox anddel_by_sendis 1 if message has been deleted by the sender form his outbox.id-sender-recipientis the primary key, andidreferences the primary keyidin another table that contains the message.
I need to determine if a message is safe to be deleted from the table once the current user has decided to do so:
from the recipient's inbox:
- if the sender has already deleted the message from his outbox (
del_by_send= 1); and - if this user is the only recipient that has not yet deleted this message from his inbox (
del_by_rec= 0 for this user, anddel_by_rec= 1 for all other recipients.)
or from the sender's outbox:
- if all recipients have deleted this message from their inboxes (
del_by_rec= 1 for all recipients of this message).
otherwise, the current user will just flag this message for deletion by setting his corresponding del_by_rec or del_by_send flag to 1.
Is there a way to efficiently query this criteria for
- the current user viewing the current message; or
- the current user mass deleting multiple messages (I'm thinking for this case a multiple-row result is to be returned).
It would be awesome to have a boolean/int returned.
For the love of me I couldn't get past this query (assuming the user is ashley and she wants to delete message 8 from her inbox):
SELECT (
(SUM(del_by_send) > 0) # sender has deleted (at least 1)
&& ((SUM(del_by_rec) + 1) >= COUNT(id)) # only 1 recipient has not deleted yet
&& ((SELECT del_by_rec FROM msg_meta WHERE recipient = 'ashley' AND id = 8) = 0) # and that recipient is this user
)
FROM msg_meta
WHERE id = 8
GROUP BY id
- This seems to do the job, but is it kinda overkill?
- This fails for multiple message
ids to avoid an expensiveforeach. I triedWHERE id IN (7,10)for recipientburtbut I couldn't quite work it into the subquery..
Help. Thanks y'all..