0

Stack Overflow. PHP and SQL novice here.

As part of a multi-user private messaging system I've been trying to write to learn how to properly interact with a database through PDO, I have two separate queries that are executed when a user deletes a message, via a single function deleteMessage():

UPDATE messages SET s_deleted = 1 WHERE id = :id AND sender = :sender
UPDATE messages SET r_deleted = 1 WHERE id = :id AND recipient = :recipient

They work well enough to accomplish what I need but running both one after the other, as I am currently doing, doesn't strike me as particularly efficient.

I looked into CASE, but as far as I could understand it wasn't quite what I needed.

Is there a way to combine these two queries so that I'm not peppering my database with extraneous requests? Would I be better off splicing each query into a separate function, i.e., deleteMessageSender() and deleteMessageRecipient()?

4

2 回答 2

1
UPDATE messages 
SET s_deleted = IF(sender = :sender, 1, s_deleted),
r_deleted = IF (recipient = :recipient, 1, r_deleted)
WHERE id = :id AND 
(sender = :sender OR recipient = :recipient);
于 2013-05-26T21:01:28.407 回答
1
UPDATE messages
SET s_deleted = IF(sender = :sender, 1, s_deleted),
    r_deleted = IF(recipient = :recipient, 1, r_deleted)
WHERE id = :id

如您所见,“技巧”是在不满足条件时简单地将列设置为其现有值,因此仅在必要时才更新。

于 2013-05-26T20:59:48.823 回答