我有:
TABLE MESSAGES
message_id | conversation_id | from_user | timestamp | message
我想:
1. SELECT * WHERE from_user <> id
2. GROUP BY conversation_id
3. SELECT in every group row with MAX(timestamp) **(if there are two same timestamps in a group use second factor as highest message_id)** !!!
4. then results SORT BY timestamp
得到结果:
2|145|xxx|10000|message
6|1743|yyy|999|message
7|14|bbb|899|message
已淘汰
1|145|xxx|10000|message <- has same timestamp(10000) as message(2) belongs to the same conversation(145) but message id is lowest
5|1743|me|1200|message <- has message_from == me
具有相同时间戳的示例组
我希望从第3组开始,但我从查询
获得第2行SELECT max(message_timestamp), message_id, message_text, message_conversationId
FROM MESSAGES
WHERE message_from <> 'me'
GROUP BY message_conversationId
ORDER by message_Timestamp DESC
我想从message_id&amp;&amp;时间戳,然后得到最大???
答案 0 :(得分:2)
您的查询是基于GROUP BY
的非标准使用(我认为SQLite仅允许与MySQL兼容)并且我完全不确定它是否会始终产生确定的结果。
另外,它在连接列上使用MAX()
。除非你以某种方式确保两个(连接的)列具有固定的宽度,否则结果也不准确。
我会写这样的查询:
SELECT
m.message_timestamp,
m.message_id,
m.message_text,
m.message_conversationId
FROM
( SELECT message_conversationId -- for every conversation
FROM messages as m
WHERE message_from <> 'me'
GROUP BY message_conversationId
) AS mc
JOIN
messages AS m -- join to the messages
ON m.message_id =
( SELECT mi.message_id -- and find one message id
FROM messages AS mi
WHERE mi.message_conversationId -- for that conversation
= mc.message_conversationId
AND mi.message_from <> 'me'
ORDER BY mi.message_timestamp DESC, -- according to the
mi.message_id DESC -- specified order
LIMIT 1 -- (this is the one part)
) ;
答案 1 :(得分:0)
基本上改变选择:
max(message_timestamp)
为:
max(message_timestamp || message_id)
or max(message_timestamp + message_id)
所以它会在时间戳的连接上搜索最多和message_id
PS。挖掘之后 - 只有当消息ID随时间戳增长(插入顺序被保留)时才能正常工作
编辑:
edit2:
为什么它有效呢?
SELECT max(message_timestamp+message_id), message_timestamp, message_id, message_conversationId, message_from,message_text
FROM MESSAGES
WHERE message_conversationId = 1521521
AND message_from <> 'me'
ORDER by message_Timestamp DESC
答案 2 :(得分:0)
尝试使用以下sql按组实现两次目的。
select m.*
from
Messages m
-- 3. and then joining to get wanted output columns
inner join
(
--2. then selecting from this max timestamp - and removing duplicates
select conversation_id, max(timestamp), message_id
from
(
-- 1. first select max message_id in remainings after the removal of duplicates from mix of cv_id & timestamp
select conversation_id, timestamp, max(message_id) message_id
from Messages
where message <> 'me'
group by conversation_id, timestamp
) max_mid
group by conversation_id
) max_mid_ts on max_mid_ts.message_id = m.message_id
order by m.message_id;