mysql> select * from s;
+–+–+
| id | user |
+–+–+
| 1 | 1 |
| 2 | 2 |
| 3 | 3 |
| 4 | 4 |
| 5 | 5 |
+–+–+
5 rows in set (0.00 sec)
mysql> select * from c;
+–+–+
| id | o |
+–+–+
| 3 | 0 |
| 3 | 1 |
| 4 | 1 |
| 4 | 2 |
+–+–+
4 rows in set (0.00 sec)
mysql> select * from m;
+–+–+
| user | o |
+–+–+
| 4 | 0 |
| 4 | 1 |
| 4 | 3 |
| 4 | 3 |
| 4 | 4 |
+–+–+
5 rows in set (0.00 sec)
mysql> select s.id,count(c.id),count(m.user) from s left join c on s.id=c.id left join m on s.user=m.user group by s.id;
+–+–+–+
| id | count(c.id) | count(m.user) |
+–+–+–+
| 1 | 0 | 0 |
| 2 | 0 | 0 |
| 3 | 2 | 0 |
| 4 | 10 | 10 |
| 5 | 0 | 0 |
+–+–+–+
5 rows in set (0.00 sec)
本人想统计c表中id=4 的记录数是2,m表中的记录数是5,但是结果两个都是10,不对。
有解决办法吗?谢谢
+–+–+
| id | user |
+–+–+
| 1 | 1 |
| 2 | 2 |
| 3 | 3 |
| 4 | 4 |
| 5 | 5 |
+–+–+
5 rows in set (0.00 sec)
mysql> select * from c;
+–+–+
| id | o |
+–+–+
| 3 | 0 |
| 3 | 1 |
| 4 | 1 |
| 4 | 2 |
+–+–+
4 rows in set (0.00 sec)
mysql> select * from m;
+–+–+
| user | o |
+–+–+
| 4 | 0 |
| 4 | 1 |
| 4 | 3 |
| 4 | 3 |
| 4 | 4 |
+–+–+
5 rows in set (0.00 sec)
mysql> select s.id,count(c.id),count(m.user) from s left join c on s.id=c.id left join m on s.user=m.user group by s.id;
+–+–+–+
| id | count(c.id) | count(m.user) |
+–+–+–+
| 1 | 0 | 0 |
| 2 | 0 | 0 |
| 3 | 2 | 0 |
| 4 | 10 | 10 |
| 5 | 0 | 0 |
+–+–+–+
5 rows in set (0.00 sec)
本人想统计c表中id=4 的记录数是2,m表中的记录数是5,但是结果两个都是10,不对。
有解决办法吗?谢谢
解决方案
40
select s.id, (select count(*) from c where id=s.id), (select count(*) from m where id=s.id) from s