Mysql多个COUNT并加入

时间:2012-05-10 11:06:36

标签: mysql sql join count

我有桌子“树”。

我有查询:SELECT * FROMWHERE pid =10 此查询返回10个项目。

我想在结果中得到类似的东西:

id | pid | title | subElements
11 | 10  | t 1   | 12
12 | 10  | t 2   | 16
13 | 10  | t 3   | 0
...

如何构建连接查询来计算这10个项目的子项?

1 个答案:

答案 0 :(得分:1)

试试这个:

SELECT t1.id, t1.pid, t1.title , count(t2) as subElements FROM tree as t1 
LEFT JOIN tree as t2 ON t2.pid = t1.id
WHERE t1.pid=10
GROUP BY t1.id, t1.pid, t1.title