使用group by,count,group by,alias执行高级sql查询

时间:2011-10-30 14:15:56

标签: php mysql

我需要执行此查询,就像(主要的猫和子猫)

这是我的架构:

++++++++++++++++++++++++++++++++
+  id | Country     |  Parent  |
++++++++++++++++++++++++++++++++
+  1  |  India      |          |
++++++++++++++++++++++++++++++++
+  2  |  Usa        |          |
++++++++++++++++++++++++++++++++
+  3  | California  |   Usa    |
++++++++++++++++++++++++++++++++
+  4  | New York    |   Usa    |
++++++++++++++++++++++++++++++++
+  5  | New Delhi   |  India   |
++++++++++++++++++++++++++++++++
+  6  | France      |          |
++++++++++++++++++++++++++++++++

我希望得到这样的结果:

+++++++++++++++++++++++++++++++++++++++++++++++++
+  id | Country     | Num |  Childs             |
+++++++++++++++++++++++++++++++++++++++++++++++++
+  1  |  India      |  1  |  New Delhi          |
+++++++++++++++++++++++++++++++++++++++++++++++++
+  2  | Usa         |  2  | California,New York |
+++++++++++++++++++++++++++++++++++++++++++++++++
+  3  | France      |  0  |                     |
+++++++++++++++++++++++++++++++++++++++++++++++++

2 个答案:

答案 0 :(得分:3)

试试这个:

SELECT t1.id, t1.Country, 
    (SELECT COUNT(id) FROM world t2
     WHERE t2.Parent = t1.Country) as Num,
    (SELECT GROUP_CONCAT(Country) FROM world t3
     WHERE t3.Parent = t1.Country) as Childs
FROM world t1
WHERE t1.Parent IS NULL

如何运作

我的查询是由一个主要部分和两个子查询(括号之间的那些)组成的;您可以将子查询视为在主查询中执行的常规查询,该查询返回到某个字段(列)。子查询可以与主查询进行交互,因为它们可以使用SELECT或WHERE中的主要字段。

主要部分获得所有基础国家(没有父母的国家)

   SELECT t1.id, t1.Country
   FROM world t1
   WHERE t1.Parent IS NULL

第一个子查询获取(对于主要部分中的每个项目)父项为主项目的国家/地区的计数

SELECT COUNT(id) FROM world t2
WHERE t2.Parent = t1.Country

请注意,在WHERE子句中,我要求将子查询ID与父ID匹配,因此我只获得与主项目相关的国家/地区数量。
第二个子查询与第​​一个子查询类似,但使用GROUP_CONCAT函数返回一个不同的字段,以便用逗号分隔所有子语句。

答案 1 :(得分:-1)

结帐GROUP_CONCAT