0

我有这个现有的 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因此主题是第一位的。

4

1 回答 1

1

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

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;
于 2013-08-29T23:07:27.537 回答