id[int] - sender[int] - receiver[int] - conv_id[bigint] - received[int] - stamp[int]
1 2 1 5 1 timestamp+1
2 2 1 5 1 timestamp+2
3 3 1 6 1 timestamp+3
4 4 1 7 1 timestamp+4
5 5 1 8 1 timestamp+5
6 5 1 8 1 timestamp+6
现在我很有意思一个按接收器分组的结果,限于3个发件人并按邮票DESC排序。怎么做?
我已经有了这个,但它正在接收所有消息,我相信这不是不松动性能的最好方法,即使我真的不是mysql的大师:
SELECT id, sender, receiver, conv_id FROM
(SELECT m.id, m.sender, m.receiver,m.conv_id
FROM messages AS m WHERE m.receiver = 1 AND m.received = 1
ORDER BY m.stamp DESC) as messages_tmp
WHERE receiver = 1 GROUP BY conv_id ORDER BY NULL LIMIT 0,3
这应该按顺序返回这些结果:
id = 6, id = 4, id = 3
对于m.received = 0
而言,m.received = 1
以及对于{{1}}的结果,如果没有足够的结果,我已经在做了这件事。到目前为止,我的数据库并不是太大,但如果它变得越来越大,恐怕它可能会很慢。我正在考虑限制子查询结果的可能性,但不知道如何做到这一点,并确保在GROUP之后我会得到足够的结果。
感谢。
答案 0 :(得分:1)
SELECT id, sender, receiver,conv_id
FROM messages WHERE receiver = 1 AND received = 1
GROUP BY conv_id
ORDER BY id DESC LIMIT 3