gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 03:17:20 25 4
gpt4 key购买 nike

<分区>

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

此外,计数应仅针对指定的 user_id。

表 1 列

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

表 2 列

+----+-------------+---------+
| 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

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com