我的数据位于 table_1
和 table_2
中。
表_1
id id_1 num ids_2
1 3 33 666,777,888
2 3 333 6666,7777,8888
3 4 44 111,222,333
4 4 444 1111,2222,3333
表_2
id_2 num
111 1
222 2
333 3
1111 1
2222 2
3333 3
666 6
777 7
888 8
6666 6
7777 7
8888 8
我只知道如何通过两步来做我想做的事:
首先左连接得到:
SELECT t1.id_1, sum(t2.num)
FROM table_1 AS t1
LEFT JOIN table_2 AS t2
ON FIND_IN_SET(t2.id_2, t1.ids_2)
GROUP BY t1.id_1;
id_1 sum(t2.num)
3 6+7+8+6+7+8
4 1+2+3+1+2+3
然后再次与 table_1 LEFT JOIN 得到 sum(table_1.num)+sum(table_2.num):
id_1 sum(table_1.num)+sum(table_2.num)
3 6+7+8+6+7+8+33+333
4 1+2+3+1+2+3+44+444
我可以只用一条 SQL 来完成吗?
最佳答案
<强> Here is the SQLFIddel Demo
以下是您可以尝试的查询
SELECT A.id_1, sum(B.num)+sum(distinct A.num)
FROM table_1 AS A
LEFT JOIN table_2 AS B
on FIND_IN_SET(B.id_2, A.ids_2)
GROUP BY A.id_1;
关于MySQL如何先对子组求和,然后对总和求和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19562595/