我有这个SQL(SQLite数据库),它正确地从messages_id分组的消息表中获取最新消息,其中消息的会话ID不是'none'。
SELECT * from messages
WHERE _id
IN (
SELECT MAX(_id)
FROM messages
WHERE conversation_id != 'none'
GROUP BY conversation_id
)
但是,我想在对话表中使用“unseenreplies”列(其中包含对此会话的看不见的回复的数量),以订购出来的消息。< / p>
我试过这个:
SELECT * from messages
WHERE _id IN
(
SELECT max(_id) from messages m
JOIN conversations c
ON m.conversation_id = c.cid ORDER BY
c.unseenreplies DESC
where m.conversation_id != 'none' group by m.conversation_id )
但是我在'where'子句附近遇到语法错误。
仅作为解释,'conversation id'不是会话表的主键,而是标识符字符串。
我该如何解决这个问题?我的方法是否以JOIN方式关闭?
答案 0 :(得分:1)
JOIN
代替IN
谓词:
SELECT *
from messages AS m1
INNER JOIN conversations c1 ON m1.conversation_id = c1.cid
INNER JOIN
(
SELECT max(_id) AS MAxId
from messages m
where m.conversation_id != 'none'
GROUP BY m.conversation_id
) AS m2 ON m1._id = m2.MaxId
ORDER BY c.unseenreplies DESC
答案 1 :(得分:0)
您无需删除in
语句即可使其生效。关键是conversations
和messages
之间的联接:
SELECT m.*
from messages m join
conversations c
on m.conversation_id = c.cid
WHERE _id
IN (
SELECT MAX(_id)
FROM messages
WHERE conversation_id != 'none'
GROUP BY conversation_id
)
order by c.unseenreplies desc
另外,请注意,这只会从messages
表而不是所有列中提取列。