SQL中有多个但是单独的WHERE条件?

时间:2013-10-24 02:40:07

标签: php sql

我正在尝试从数据库中获取用户消息,其中用户是发件人或具有另一个唯一用户的收件人,我无法弄清楚如何编写WHERE语句。这就是我现在所拥有的:

$sql = " SELECT sender, 
       receiver, 
       timestamp, 
       message 
FROM   messages 
WHERE  ( receiver = '$log_username' 
         AND sender = '$messageOther' ) 
        OR ( receiver = '$messageOther' 
             AND sender = '$log_username' ) 
ORDER  BY timestamp DESC";
$query = mysqli_query($db_conx, $sql);
while($row = mysqli_fetch_array($query, MYSQLI_ASSOC)) {
    $message = $row["message"];
    $sender = $row["sender"];
    $receiver = $row["receiver"];
    $timestamp = $row["timestamp"];
    $messagehtml .= 'Sender: '.$sender.' | Receiver: '.$receiver.' | Message: '.$message.' | Timestamp '.$timestamp.'<br />';
    }

写这个以获得结果的最佳方式是什么?

1 个答案:

答案 0 :(得分:0)

如果您的意思是$log_username应该是senderreceiver而另一个值$messageOther应该是senderreceiver查询将适合您:

SELECT sender, receiver, timestamp, message 
FROM messages 
WHERE ((receiver='$log_username' AND sender='$messageOther') OR
(receiver='$messageOther' AND sender='$log_username'))
ORDER BY timestamp DESC

sqlfiddle

好而不是AND你需要在任何地方使用OR。尝试以下,它适用于我的测试表:

SELECT sender, receiver, timestamp, message 
FROM messages 
WHERE ((receiver='$log_username' AND receiver='$messageOther') OR
(sender='$messageOther' AND sender='$log_username'))
ORDER BY timestamp DESC

<击>