2013-05-19 37 views
1

我有這個SQL(SQLite數據庫),它正確地從message_table中按照conversation_id分組,其中消息具有非'none'對話標識的消息表中的最新消息。SQL:在另一個表中按列desc排序

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

不過,我想使用在談話表中的「unseenreplies」列(其中有看不見回覆的數量計數爲這次談話),以爲了出來的消息。

我已經試過這樣:

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) 

,但我得到了「其中」條款附近的語法錯誤。

只是通過解釋'會話ID'不是會話表的主鍵,而是一個標識符字符串。

我該如何解決這個問題?我的JOIN方式關閉嗎?

+0

馬哈茂德給了你一個可以工作的查詢。你遇到的問題是你的子句的順序。你在where子句前有order by子句。按子句排序幾乎總是查詢的最後一個子句。 –

回答

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 
0

您不必刪除in語句來得到這個工作。關鍵是加入conversationsmessages之間:

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表拉列,而不是所有的列。