2014-02-14 22 views
0

我有一个简单的版本控制系统的博客系统。我的DB是:得到子查询并计为colomn

|id------|parent_id|title------------------| 
|1  |1  |Test title    | 
|2  |1  |Test title 2   | 
|3  |1  |Last test title  | 
|4  |4  |Another blog item  | 

我的查询只得到最新的版本(仅3和4):

SELECT * FROM 
(SELECT * FROM blogs ORDER BY id DESC) b 
GROUP BY b.parent_id 

结果:

  • 最后测试题
  • 另一个博客item

我的问题是:是可以统计的所有子版本的数量?这样的:

  • 最后测试题(3)
  • 另一个博客项(1)
+0

是的,这是可能的。 – hjpotter92

回答

1

您查询是不能保证工作。您可以通过扩展here了解MySQL组。基本上,*产生的字段不能保证来自“第一”记录。我想强调,这被记录为不起作用,即使它可能在实践中起作用。

写您的查询的另一种方法是:

select b.*, p.numchildren 
from (select parent_id, max(id) as maxid, count(*) as numchildren 
     from blogs 
     group by parent_id 
    ) p join 
    blogs b 
    on b.id = p.maxid 
order by b.parent_id 
+0

谢谢戈登!这是我想要的! – angelique000