我在确定如何为我在下面复制的查询创建case语句时遇到问题。本质上,查询所做的只是从messages_messages查询当前用户发送的行($ userid)或发送的原始线程($ threadid)的发送者。除了线程的原始发件人之外,这对每个人来说都是完美的选择,谁应该能够提取与线程相关的所有消息。
基本上我需要添加以下语句的SQL等价物:
WHERE messages_threads.id = $threadid
if($userid == messages_threads.senderid) {
// Don't add an AND clause
} else {
// Add the following AND clause
AND (messages_messages.senderid = $userid OR messages_messages.senderid = messages_threads.senderid)
}
以下是我目前使用的查询:
SELECT messages_messages.id, messages_messages.senderid, username AS sendername, pictures.url AS picture, body, UNIX_TIMESTAMP(time) AS unixtimestamp
FROM messages_messages
JOIN messages_threads ON messages_threads.id = messages_messages.threadid
JOIN users ON messages_messages.senderid = users.id
LEFT JOIN pictures ON messages_messages.senderid = pictures.userid AND pictures.profile = 1
WHERE messages_threads.id = $threadid
AND (messages_messages.senderid = $userid OR messages_messages.senderid = messages_threads.senderid)
ORDER BY time ASC
答案 0 :(得分:1)
任何if语句系列都可以转换为AND和OR:
WHERE messages_threads.id = $threadid AND
($userid=messages_threads.senderid OR
(messages_messages.senderid = $userid OR
messages_messages.senderid = messages_threads.senderid))
如果$userid==messages_threads.senderid
为真,则整个or
子句为真,因此不检查任何其他内容。如果它是假的,则检查该子句的其余部分。