我有:
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 和 timestamp 做 union 然后得到 max 是什么意思???
最佳答案
您的查询基于 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)
) ;
关于android - sqlite3按最大值查询并按第二个因素过滤,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32779941/