【问题标题】:SQL: Order by column desc in another tableSQL:在另一个表中按列 desc 排序
【发布时间】:2013-05-19 11:34:00
【问题描述】:

我有这个 SQL(SQLite 数据库),它正确地从按会话 ID 分组的消息表中获取最新消息,其中消息的会话 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 方法是否可行?

【问题讨论】:

  • Mahmoud 为您提供了一个可行的查询。你遇到的问题是你的条款的顺序。您在 where 子句之前有 order by 子句。 Order by 子句几乎总是查询的最后一个子句。

标签: sql sqlite join max


【解决方案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 

【讨论】:

    【解决方案2】:

    您不必删除in 语句即可使其正常工作。关键是conversationsmessages之间的join:

    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 表中提取列,而不是所有列。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-01-12
      • 2020-09-08
      • 2012-10-31
      • 2011-04-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多