按表MYSQL的最新消息排序

时间:2013-08-29 22:05:44

标签: mysql sql

我有这个现有的MYSQL查询,我想调整,但我不知道如何。我想调整它,以便按照每个主题上发布的最新消息对topic进行排序。

以下是我目前的情况:

select
  t.*,
  coalesce(s.StarCount, 0) as StarCount,
  coalesce(m.UserCount, 0) as UserCount,
  coalesce(m.MessageCount, 0) as MessageCount
from
  Topics t
  left join (
    select 
      topic, 
      count(distinct user) as UserCount,
      count(*) as MessageCount
     from Messages
     group by topic
  ) m ON m.topic = t.topic
  left join (
   select 
    topic, 
    count(*) as StarCount
   from Stars_Given
   group by topic
 ) s ON s.topic = t.topic
ORDER BY UserCount DESC, topicID DESC
LIMIT 0,15

最佳答案将是此代码,但已经过调整。

以下是我的表格样本。

讯息

 MessageID    User      Message      Topic    Time
 1            Tom       Hi           ball     9:00am
 2            John      Hey          book     10:00am
 3            Mike      Sup          book     8:00am
 4            Mike      Ok           book     11:00am

主题

 topicID    Topic      Title     Category1    Category2
 1          ball       Sports    Action       Hot
 2          book       School    Study        Hot

Stars_Given

 starID     Topic
 1          ball
 2          book
 3          book
 4          book

我想最终:

Topic_Review

 Topic    Title     StarCount    UserCount    MessageCount
 book     school    3            2            3
 ball     Sports    1            1            1

注意:book的主题是Messages表中使用的最新主题,因此该主题是第一个。

1 个答案:

答案 0 :(得分:1)

您的查询几乎就在那里。您只需要将最大时间戳添加到消息子查询中。这是maxt子查询中的m列:

select t.*, coalesce(s.StarCount, 0) as StarCount, coalesce(m.UserCount, 0) as UserCount,
       coalesce(m.MessageCount, 0) as MessageCount
from Topics t left join
     (select topic, count(distinct user) as UserCount, count(*) as MessageCount,
             max(time) as maxt
     from Messages
     group by topic
    ) m
    ON m.topic = t.topic left join
    (select topic, count(*) as StarCount
     from Stars_Given
     group by topic
    ) s
    ON s.topic = t.topic
ORDER BY maxt desc, UserCount DESC, topicID DESC
LIMIT 0, 15;