Sqlite 如何在一个查询中执行多个查询?
我正在构建一个聊天应用程序,使用Firebase发送和接收消息。发送或接收消息后,我将其存储到SQLite,如下所示。现在是最近的聊天屏幕,我需要所有唯一聊天的最后一条消息,在我观察SQLite数据库时,在一次查询中,这些唯一聊天中未读消息的数量Sqlite 如何在一个查询中执行多个查询?,sqlite,Sqlite,我正在构建一个聊天应用程序,使用Firebase发送和接收消息。发送或接收消息后,我将其存储到SQLite,如下所示。现在是最近的聊天屏幕,我需要所有唯一聊天的最后一条消息,在我观察SQLite数据库时,在一次查询中,这些唯一聊天中未读消息的数量 Mid(STRING) | SentBy | SentTo | message | readTime | sentTime| Type ----------------+--------+--------+---------+---------
Mid(STRING) | SentBy | SentTo | message | readTime | sentTime| Type
----------------+--------+--------+---------+----------+---------+------
A | AA | JD | M1 | 1 | 0 | S
B | JD | AA | M2 | 2 | 1 | s
C | AA | JD | M3 | 3 | 2 | s
D | AB | JD | m5 | null | 3 | s
E | AA | JC | M1 | 5 | 4 | s
F | JD | AB | M2 | 6 | 5 | s
G | AA | JD | M3 | 7 | 6 | s
H | AA | JC | m5 | 8 | 7 | s
I | AA | JD | M1 | null | 8 | s
J | JD | AA | M2 | 10 | 9 | s
K | AA | JD | M3 | 11 | 10 | s
L | AB | JC | m5 | 12 | 11 | s
M | AA | JD | M1 | 13 | 12 | s
N | JC | AA | M2 | 14 | 13 | s
O | AB | JD | M3 | 15 | 14 | s
P | JC | JD | m5 | 16 | 15 | s
我试过了
SELECT *,COUNT() FROM messagesTable GROUP BY min ( sentBy, sentTo ), max( sentBy , sentTo ) ORDER BY sentTime desc
这个查询提供了sentTo和sentBy的每个组合的最后消息。但我还需要知道有多少信息是未读的组合。我想对每一行运行一个查询,如
SELECT COUNT() FROM messagesTable WHERE sentBy = message.sentBy, sentTo = message.sentTo, readTime = null
如何在一个查询中同时运行两个查询?您必须通过组合
(sentby,sentto)
进行分组,并通过直接的计数(*)
获得消息总数,通过条件聚合可以获得未读消息的数量。然后将结果连接到表中,以获得最后一条消息:
select
g.user1, g.user2, g.lasttime, m.message lastmessage,
g.totalcounter, g.unreadcounter
from messagestable m inner join (
select
min(sentby, sentto) user1, max(sentby, sentto) user2,
max(senttime) lasttime, count(*) totalcounter,
sum(case when readtime is null then 1 else 0 end) unreadcounter
from messagestable
group by user1, user2
) g
on g.user1 = min(m.sentby, m.sentto) and g.user2 = max(m.sentby, m.sentto)
and g.lasttime = m.senttime
order by g.lasttime desc
请参阅。结果:
你在使用sqlite 3.25或更新版本吗?我不是很清楚sure@VnsAditya请注意,当前的第一个查询可能不会按您的要求提供输出中每个会话的最新消息。@VnsAditya此答案有悬赏,是否已撤销?。请注意,OP声明他们也希望输出中每个会话的最新消息。
| user1 | user2 | lasttime | lastmessage | totalcounter | unreadcounter |
| ----- | ----- | -------- | ----------- | ------------ | ------------- |
| JC | JD | 15 | m5 | 1 | 0 |
| AB | JD | 14 | M3 | 3 | 1 |
| AA | JC | 13 | M2 | 3 | 0 |
| AA | JD | 12 | M1 | 8 | 1 |
| AB | JC | 11 | m5 | 1 | 0 |