1

私はこの SQL (SQLite データベース) を持っています。これは、メッセージが「none」以外の会話 ID を持つ conversation_id でグループ化されたメッセージ テーブルから最新のメッセージを正しく取得します。

SELECT * from messages 
WHERE _id
IN ( 
   SELECT MAX(_id)
   FROM messages
   WHERE conversation_id != 'none'
   GROUP BY conversation_id
   ) 

ただし、会話テーブルの「見えない返信」列 (この会話の見えない返信の数を含む) を使用して、出てくるメッセージを並べ替えたいと思います。

私はこれを試しました:

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 を使用した私のアプローチは間違っていますか?

4

2 に答える 2

1

JOININ述語の代わりにそれらを:

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 
于 2013-05-19T11:44:25.243 に答える
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また、これはすべての列ではなく、テーブルから列のみをプルすることに注意してください。

于 2013-05-19T13:29:33.297 に答える