我正在尝试从数据库中获取用户消息,其中用户是发件人或具有另一个唯一用户的收件人,我无法弄清楚如何编写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 />';
}
写这个以获得结果的最佳方式是什么?
答案 0 :(得分:0)
如果您的意思是$log_username
应该是sender
或receiver
而另一个值$messageOther
应该是sender
或receiver
查询将适合您:
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
好而不是 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
击> <击> 撞击>