假设我有这个表结构:
CREATE TABLE `test` (
`id` int(11) NOT NULL auto_increment,
`type` varchar(128) default NULL,
`subtype` varchar(128) default NULL,
KEY `id` (`id`));
而这个数据:
INSERT INTO `test` VALUES (1,'a','1'),(2,'a','2'),(3,'a','3'),(4,'a','4'),(5,'b','4'),
(6,'c','4'),(7,'c','1'),(8,'c','2'),(9,'c','2');
我可以做这个:
SELECT test.type, test.subtype, count(test.subtype) as countsubtype, testbytype.counttype
FROM (test)
LEFT JOIN (SELECT type, count(type) AS counttype FROM test group by type) AS testbytype ON test.type = testbytype.type
GROUP by type, subtype;
+------+---------+--------------+-----------+
| type | subtype | countsubtype | counttype |
+------+---------+--------------+-----------+
| a | 1 | 1 | 4 |
| a | 2 | 1 | 4 |
| a | 3 | 1 | 4 |
| a | 4 | 1 | 4 |
| b | 4 | 1 | 1 |
| c | 1 | 1 | 4 |
| c | 2 | 2 | 4 |
| c | 4 | 1 | 4 |
+------+---------+--------------+-----------+