我遇到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将保持在同一位置,完全没有变化。解决这个问题,让我知道这里有什么问题。
答案 0 :(得分: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
希望它能像你现在想的那样工作!
答案 1 :(得分:0)
如果我理解你的问题,那么:
SELECT m_from, max(m_time) as max_time from messages where m_to = 5 group by m_from order by max_time desc;
应该适合你。
答案 2 :(得分: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