MYSQL查询问题:选择所有线程,按与线程对应的no的数量顺序排序

时间:2011-04-25 17:21:21

标签: mysql select

我的标题可能有点令人困惑,所以这是我的问题。

这是我的表:

CREATE TABLE `b_posts` (
  `thread` int(12) NOT NULL,
  `no` int(12) NOT NULL,
  `comment` text NOT NULL,
  `gone` int(1) NOT NULL default '0',
  PRIMARY KEY  (`no`),
  FULLTEXT KEY `comment` (`comment`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1;

我现在需要一个查询,它选择所有没有消失的线程(意味着消失为0,如果完成为1则这意味着该线程已被删除)。选择线程的顺序应该是与原始线程具有相同线程的no的数量。

进一步解释:

thread | no | comment | gone
100 | 100 | hello there, this is the thread! | 0
100 | 102 | this is a reply in the thread 100 | 0
100 | 103 | another reply in the same thread | 0
104 | 104 | this is a different thread | 0
104 | 105 | a reply to the different thread | 0

我现在想用我的查询按以下顺序获取以下数据:

thread | no | comment | gone
100 | 100 | hello there, this is the thread! | 0
104 | 104 | this is a different thread | 0

(线程启动器是在thread == no时定义的)

1 个答案:

答案 0 :(得分:0)

由于您的限定符“thread = no”和“gone = 0”,我认为将它们包含在结果列中没有意义...但是,我确实包含了每个线程的总条目的子计数

select b.thread,
       b.comment,
       postCounts.TotalEntries
   from
      b_posts b
         join ( select b2.thread, count(*) as TotalEntries 
                    from b_posts b2
                    group by b2.thread ) postCounts
            on b.thread = postcounts.thread
   where
          b.thread = b.no
      and b.gone = 0
   order by
      postCounts.TotalEntries DESC