我想從子表中計算一些列。我的表結構如下:來自子表的SQL計數
人
+---+----------+--------+
| Pid | Name |Surname |
+---+----------+--------+
| 1 | Per A | D |
| 2 | Per B | E |
| 3 | Per C | F
+----+---------+--------+
童車
+---+---------+-------------------+------------+-----+
| Cid | CName | School | Sex | Pid |
+---+---------+-------------------+------------+-----+
| 1 | John | High | Man | 1 |
| 2 | Alice | Primary | Woman | 2 |
| 3 | Mel | High | Man | 3 |
| 4 | Angelina | High | Woman | 2 |
+----+---------+------------------+------------+-----+
所以我想輸出
+---+----------+------+---------+--------+---+--------------+
| Pid| PerName | High | Primary | Woman | Man | ChildCount |
+---+----------+------+---------+--------+-----+------------+
| 1 | Per A | 1 | 0 | 0 | 1 | 1 |
| 2 | Per B | 1 | 1 | 2 | 0 | 2 |
| 3 | Per C | 1 | 0 | 0 | 1 | 1 |
+----+---------+------+---------+--------+-----+------------+
我怎樣才能得到這個輸出?
我嘗試這種方法,但我有更多的列這樣計算屬於子表。所以我得到緩慢的查詢結果。
select Pid,Name,Surname,
(select count(*) from Childs where Persons.Pid=Childs.Pid) ChildCount,
(select count(*) from Childs where Persons.Pid=Childs.Pid and School='Primary') Primary
from Persons
JOIN表。做一個GROUP BY。 – jarlh
我想只用Pid分組,但SQL想要其他列也像名稱,姓氏等如果在MySQL中沒有問題,但在MSSQL問題 – mbayrak
較新的MySQL版本不會讓你做無效的GROUP BY - 除非在兼容模式。 – jarlh