Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/sql/87.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 具有三个表的行计数MySQL_Php_Sql_Mysql_Count_Rowcount - Fatal编程技术网

Php 具有三个表的行计数MySQL

Php 具有三个表的行计数MySQL,php,sql,mysql,count,rowcount,Php,Sql,Mysql,Count,Rowcount,我的MySQL数据库看起来像这样 **table_schools** id | name 1 | school_1 2 | school_2 **table_classes** id | class | school_id 1 | a | 1 2 | b | 1 3 | c | 2 4 | d | 2 5 | e | 2 **table_students** id | name | class_id 1 | Nick | 1 2

我的MySQL数据库看起来像这样

**table_schools**
id | name
1  | school_1
2  | school_2

**table_classes**
id | class | school_id
1  | a     | 1
2  | b     | 1
3  | c     | 2
4  | d     | 2
5  | e     | 2

**table_students**
id | name  | class_id
1  | Nick  | 1
2  | Tom   | 2
3  | Kevin | 3
4  | Jane  | 4
5  | Mark  | 5
6  | Tim   | 5
7  | Lynn  | 5
我希望有这样的输出:

school_name | class_count | student_count
school_1    | 2           | 2
school_2    | 3           | 5
有没有一种方法可以在一个sql查询中实现这一点?怎么做

SELECT table_schools.name, COUNT(table_classes.name) AS classes, COUNT(table_students.id) AS students
FROM table_schools
LEFT JOIN table_classes ON table_schools.id = table_classes.school_id
LEFT JOIN table_students ON table_students.class_id = table_classes.id
GROUP BY table_schools.id, table_classes.id
ORDER BY table_schools.name
SELECT  s.name, COUNT(DISTINCT c.id) AS classes, COUNT(st.id) AS students
FROM    table_schools s
LEFT JOIN
        table_classes c
ON      c.school_id = s.id
LEFT JOIN
        table_students st
ON      st.class_id = c.id
GROUP BY
        s.id