我有一个如下所示的Messages表:
Messages +-----+------------+-------------+--------------+ | id | sender_id | receiver_id | created_at | +-----------------------------------------------+ | 1 | 1 | 2 | 1/1/2013 | | 2 | 1 | 2 | 1/1/2013 | | 3 | 2 | 1 | 1/2/2013 | | 4 | 3 | 2 | 1/2/2013 | | 5 | 3 | 2 | 1/3/2013 | | 6 | 5 | 4 | 1/4/2013 | +-----------------------------------------------+
如果’thread’是给定sender_id和receiver_id之间的一组消息,我希望查询返回最近10个线程的最新10条消息,其中sender_id或receiver_id是给定的id.
给定user_id为5的预期输出:
+-----+------------+-------------+--------------+ | id | sender_id | receiver_id | created_at | +-----------------------------------------------+ | 1 | 5 | 2 | 1/4/2013 | | 2 | 5 | 2 | 1/4/2013 | | 3 | 2 | 5 | 1/4/2013 | | 4 | 3 | 5 | 1/4/2013 | | 5 | 5 | 2 | 1/3/2013 | | 6 | 5 | 4 | 1/3/2013 | +-----------------------------------------------+
例如,用户5和2之间(上面有4个)和10个线程的限制(上面有3个)之间的最多10个消息的限制.
我一直在使用子查询尝试这种查询,但没有设法获得不同线程数量的第二个限制.
SELECT * FROM (SELECT DISTINCT ON (sender_id,receiver_id) messages.* FROM messages WHERE (receiver_id = 5 OR sender_id = 5) ORDER BY sender_id,receiver_id,created_at DESC) q ORDER BY created_at DESC LIMIT 10 OFFSET 0;
我正在考虑创建一个新的Thread表,其中包含一个thread_id字段,该字段将是sender_id receiver_id的串联,然后只是加入Messages,但我有一种偷偷摸摸的怀疑,它只能用一个表来实现.