如何对每个表进行分组计数并按列打印?

时间:2018-11-13 16:08:42

标签: mysql

在这里,我有两个表,每个表都有监管字段和user_id字段。我希望对表和打印的每个监督进行分组计数,如下所示。两个表都包含不同的数据。

也应仅针对指定的user_id进行计数。

表1列

+----+-------------+---------+
| id | supervision | user_id |
+----+-------------+---------+
|  1 | type1       |       2 |
|  2 | type1       |       2 |
|  3 | type2       |      1  |
|  4 | type1       |       2 |
|  5 | type2       |       2 |
+----+-------------+---------+

Table2列

+----+-------------+---------+
| id | supervision | user_id |
+----+-------------+---------+
|  1 | type3       |       2 |
|  2 | type1       |       2 |
|  3 | type3       |       1 |
|  4 | type1       |       2 |
|  5 | type2       |       2 |
+----+-------------+---------+

对于user_id=2,它应该给出如下输出:

+-------+--------+--------+
| Type  | table1 | table2 |
+-------+--------+--------+
| type1 |      3 |      2 |
| type2 |      1 |      1 |
| type3 |      0 |      1 |
| ....  |        |        |
+-------+--------+--------+

现在,我尝试使用该查询为table2的table1提供正确的结果。

select t1.supervision,
       count(t1.supervision) AS table1,
       count(t2.supervision) AS table2 from table1 t1 
LEFT JOIN 
table2 t2 ON t1.id=t2.id 
where t1.userid=2 AND t2.userid=2  
group by t1.supervision

1 个答案:

答案 0 :(得分:0)

SELECT t1.supervision, count(t1.id) AS table1, count(t2.id) AS table2
FROM users u
LEFT JOIN table1 t1 on (t1.user_id = u.id)
LEFT JOIN table2 t2 on (t2.user_id = u.id)
WHERE u.id = 2
GROUP BY t1.supervision

这假定用户表存在。您遇到的问题是type3在t1中没有退出,因此左联接将不包含那里的值,而您是在id上联接,而不是在user_id上联接。