1

我的mysql查询有问题,有人可以解决这个问题吗?这是数据

        m_to    m_from  m_id    m_time 
        5       5       1       1374769716
        5       5       2       1374771178
        5       5       3       1374771294
        5       5       4       1374771396
        5       5       5       1374771784
        1       5       6       1374772120
        1       5       7       1374773097
        5       1       8       1374773579
        5       1       9       1374774095
        5       1       10      1374774148
        1       5       11      1374777304
        444     5       12      1374779752
        5       444     13      1374780378
        5       5       14      1374781374
        5       5       15      1374832375
        444     5       16      1374837258
        5       444     17      1374837525
        5       444     18      1374838801
        444     5       19      1374838976
        1       5       20      1374842736
        5       5       21      1374842954
        444     5       22      1374843389
        5       5       23      1374843466
        1       5       24      1374843853
        1       5       25      1374848855
        444     5       26      1374848889
        5       5       27      1374848912
        1       5       28      1374849001
        5       5       29      1374849056
        444     5       30      1374850406

第一列为“m_to”,第二列为“m_from”,第三列为“m_id”,第四列为“m_time”

现在我想要的是,我想按 m_from 分组并按 m_time 排序。但是将要添加的新消息应该在顶部,下一行应该在第二个......等等

我用过。

SELECT m_from,m_time
FROM messages
WHERE m_to='5'
GROUP BY m_from
ORDER BY m_time DESC

但结果是这样的

444
1
5

所以,它没有正确排序数据..

现在,如果在 5 处添加新消息,那么 5 将保持在同一位置,完全没有变化。解决这个问题,让我知道我在这里做错了什么。

4

3 回答 3

1

您可以通过执行以下操作获取与最后一条消息相对应的 m_from 以显示在列表顶部:

 SELECT m_from, MAX(m_time) AS m_time
 FROM messages 
 WHERE m_to = 5
 GROUP BY m_from 
 ORDER BY m_time DESC

结果是:

5   1374849056
444 1374838801
1   1374774148

如果我添加一个条目:

INSERT INTO messages
    (m_to, m_from, m_id, m_time)
VALUES
    (5, 1, 31, 1374850416);

我现在得到:

1   1374850416
5   1374849056
444 1374838801

这就是你想要的......你肯定在测试中的某个地方犯了一个错误,因为它工作正常!

新编辑:

所以,根据你现在所说的,试试这个:

SELECT m_user, MAX(m_id) as m_id, MAX(m_time) AS m_time
FROM (
SELECT m_from AS m_user, MAX(m_id) as m_id, MAX(m_time) AS m_time
 FROM messages 
 WHERE m_to = 5
 GROUP BY m_from
UNION
SELECT m_to AS m_user, MAX(m_id) as m_id, MAX(m_time) AS m_time
 FROM messages 
 WHERE m_from = 5
 GROUP BY m_to
 ) AS result
GROUP BY m_user
ORDER BY m_time DESC

希望它会像你现在想要的那样工作!

于 2013-07-26T16:51:55.210 回答
0

尝试这个

   SELECT m_from, max(m_time) as time from messages 
   where m_to = 5 group by m_from order by time desc;

在这里演示

这将给出输出

M_FROM  TIME
 5      1374849056
 444    1374838801
 1      1374774148
于 2013-07-26T16:53:19.937 回答
0

If I understand your problem correctly then this:

SELECT m_from, max(m_time) as max_time from messages where m_to = 5 group by m_from order by max_time desc;

should work for you.

于 2013-07-26T16:52:09.693 回答