对 MYSQL 中多个表的行进行计数和合并
Counting and combining rows across multiple tables in MYSQL
我想计算一个变量在多个 table 行中出现的次数,然后将它们组合起来得到如下输出:
Output Table
user id | A count | B count | C count | Total count
------------------------------------------------
1 | * | * | * | *
2 | * | * | * | *
3 | * | * | * | *
来自 table 具有以下结构:
Table A, B, C etc
x | y | user id |
-------------------------------
* | * | 2
* | * | 4
* | * | 1
* | * | 1
This question 处理单个 table 中的计数,但我不确定如何将解决方案应用于多个 table 以获得如上所示的输出。理想情况下,我会输出到 CSV。任何帮助将不胜感激。
示例数据(查看评论以回答标记为正确的)
user_id a b c a+b+c
1 18266 238640 2022 258928
70 67 200 19 286
596 2 3 6 11
759 56 606 67 729
760 2 5 5 12
1122 194 1030 220 1444
1194 26 2 2 30
1298 195 466 2 663
SELECT user_id, SUM(a), SUM(b), SUM(c), SUM(a) + SUM(b) + SUM(c)
FROM
(
SELECT user_id, count(*) a, 0 b, 0 c FROM A GROUP BY user_id
UNION ALL
SELECT user_id, 0, count(*), 0 FROM B GROUP BY user_id
UNION ALL
SELECT user_id, 0, 0, count(*) FROM C GROUP BY user_id
) tmp
GROUP BY user_id
我想计算一个变量在多个 table 行中出现的次数,然后将它们组合起来得到如下输出:
Output Table
user id | A count | B count | C count | Total count
------------------------------------------------
1 | * | * | * | *
2 | * | * | * | *
3 | * | * | * | *
来自 table 具有以下结构:
Table A, B, C etc
x | y | user id |
-------------------------------
* | * | 2
* | * | 4
* | * | 1
* | * | 1
This question 处理单个 table 中的计数,但我不确定如何将解决方案应用于多个 table 以获得如上所示的输出。理想情况下,我会输出到 CSV。任何帮助将不胜感激。
示例数据(查看评论以回答标记为正确的)
user_id a b c a+b+c
1 18266 238640 2022 258928
70 67 200 19 286
596 2 3 6 11
759 56 606 67 729
760 2 5 5 12
1122 194 1030 220 1444
1194 26 2 2 30
1298 195 466 2 663
SELECT user_id, SUM(a), SUM(b), SUM(c), SUM(a) + SUM(b) + SUM(c)
FROM
(
SELECT user_id, count(*) a, 0 b, 0 c FROM A GROUP BY user_id
UNION ALL
SELECT user_id, 0, count(*), 0 FROM B GROUP BY user_id
UNION ALL
SELECT user_id, 0, 0, count(*) FROM C GROUP BY user_id
) tmp
GROUP BY user_id