3

我有一个名为 private_messages 的 SQL 表,其中包含字段(id、from、to、message、stamp)。戳字段对应于消息的日期

那么我需要什么查询:

1)获得两个用户之间的对话(按日期排序)?

我试过查询

(SELECT * FROM private_messages WHERE from=$my_id AND to=$other_id) 
UNION 
(SELECT * FROM private_messages WHERE from=$other_id AND to=$my_id) 
ORDER BY stamp
;

但不起作用...

2) 获取我和其他用户之间的最后一条消息,每个用户都有不同的用户,按日期排序(例如在 Facebook 中构建一个收件箱)?

4

4 回答 4

9

1.)

SELECT  * 
FROM    private_messages a
WHERE   (a.from = $my_id AND a.to = $other_id) OR
        (a.from = $other_id AND a.to = $my_id)
ORDER   BY stamp DESC

2.)

SELECT  f.*
FROM
        (
            SELECT  *
            FROM    private_messages a
            WHERE  (LEAST(a.from, a.to), GREATEST(a.from, a.to), a.stamp) 
                    IN  (   
                            SELECT  LEAST(b.from, b.to) AS x, 
                                    GREATEST(b.from, b.to) AS y,
                                    MAX(b.stamp) AS msg_time
                            FROM    private_messages b
                            GROUP   BY x, y
                        )
        ) f
WHERE   $my_id IN (f.from, f.to)
ORDER   BY f.stamp DESC
于 2013-01-27T06:54:31.200 回答
1

你能试试这个吗?

SELECT x.* 
FROM (SELECT * FROM private_messages 
WHERE `to`='$my_id' OR `from`='$my_id' GROUP BY `to`, `from`) AS x 
ORDER BY x.stamp DESC ;

To,From可以是保留字。注意到这x是一个表别名。

于 2013-01-27T08:06:28.597 回答
0

我过去曾这样做过,但查询很简单。可能这对你有用

      SELECT * FROM private_messages WHERE (from=$my_id AND to=$other_id) OR (from=$other_id AND to=$my_id) ORDER BY stamp
于 2013-01-27T07:13:20.690 回答
0

1) 很确定您需要在 PHP 变量周围加上引号,如下所示:

(SELECT * FROM private_messages WHERE from='$my_id' AND to='$other_id') UNION (SELECT * FROM private_messages WHERE from='$other_id' AND to='$my_id') ORDER BY stamp DESC

2)尝试类似:

SELECT * FROM (SELECT * FROM private_messages WHERE to='$my_id' OR from='$my_id' GROUP BY to, from) AS tmp_table ORDER BY stamp DESC
于 2013-01-27T07:14:54.510 回答