【发布时间】:2019-04-16 12:35:02
【问题描述】:
这里我有两个表,每个表都有监督字段和 user_id 字段。我希望对表格和打印的每个监督进行分组计数,如下所示。两个表都包含不同的数据。
count 也应该只针对指定的 user_id。
Table1 列
+----+-------------+---------+
| 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 |
| .... | | |
+-------+--------+--------+
现在这个查询我试过了,它给出了 table1 的正确结果而不是 table2。
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
【问题讨论】:
-
MySQL 还是 SQL Server?请不要标记多个数据库引擎。
-
是否有可能有一些
type*值,它们只存在于表 1 中,而不存在于表 2 中,反之亦然?
标签: mysql