2011-04-25 10 views
0

我的標題可能有點混亂,所以這是我的問題。MYSQL查詢問題:選擇所有主題,按線程對應的數量排序

這是我的表:

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,這將意味着該線程已被刪除)。線程被選擇的順序應該是與原始線程相同的線程的數量。

進一步解釋:

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 

(線程起動定義爲當線程==無)

回答

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