php mysql连接发送和接收的消息

时间:2011-09-02 19:16:19

标签: php mysql private-messaging

私人消息系统显示连接的用户消息。

•用户发送和接收按时间排序组合在一起的消息  •每个消息选项卡将显示发件人/收件人的姓名,消息和time_sent
 •有关如何提高查询速度的任何提示(例如索引等)?

MESSAGES TABLE 
--------------
id sender receiver time_sent message opened recipientDelete senderDelete

Users Table
-----------
id first_name last_name

我的尝试:

$userid = logged in user
$query="SELECT MAX(id), sender, receiver, MIN(time_sent), message, opened 
        FROM messages 
        WHERE (receiver='$userid' AND recipientDelete='0') 
             OR (sender='$userid' AND senderDelete='0') 
        GROUP BY receiver,sender 
        ORDER BY time_sent DESC LIMIT 8";

RESULT /问题:
如果登录用户(id = 3)收到来自两个用户(id = 1,id = 2)的消息,则此查询将返回从用户1和2发送的消息

第二次尝试:

 $query="SELECT MAX(id), sender, receiver, MIN(time_sent), message, opened      
     FROM ( SELECT 
              CASE WHEN sender = '$userid' THEN receiver ELSE sender END
              MIN(time_sent)
            FROM messages 
            WHERE sender = '$userid' OR receiver = '$userid' 
            GROUP BY CASE WHEN sender = '$userid' THEN receiver ELSE sender END)
         ORDER BY time_sent DESC 
         LIMIT 8";

返回错误。

1 个答案:

答案 0 :(得分:0)

您正在从派生表中进行选择。在MySQL中,该子查询必须是别名:

SELECT ...
FROM ( SELECT ...) AS subqueryalias
                   ^^^^^^^^^^^^^^^^
WHERE ...