Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/mysql/63.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/sql/86.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
MySQL如何先求子群的和,然后求和总数_Mysql_Sql - Fatal编程技术网

MySQL如何先求子群的和,然后求和总数

MySQL如何先求子群的和,然后求和总数,mysql,sql,Mysql,Sql,我的数据在表1和表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

我的数据在
表1
表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
然后再次与表_1左连接以求和(表_1.num)+求和(表_2.num):

我可以只用一个SQL完成吗?

下面是您可以尝试的查询

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;
灵感来自:

如果没有上述划分,结果将是:

id_1 total
3    6+7+8 + 6+7+8 + 33+33+33 + 333+333+333
4    1+2+3 + 1+2+3 + 44+44+44 + 444+444+444
有了分区,结果将是我想要的:

id_1 total
3    6+7+8 + 6+7+8 + 33/3+33/3+33/3 + 333/3+333/3+333/3
4    1+2+3 + 1+2+3 + 44/3+44/3+44/3 + 444/3+444/3+444/3

是的,你只能在一个SQLIn
Table_1
中完成,
id_1
num
的组合是唯一的???在Table_1中有另一个唯一的字段,比如id(Table_1 updated)。现在我的问题是,(id_1,num)列中(3,33)是否会有多个条目?不,没有。组合(id_1,num)是唯一的。请看我的答案,我认为更好的解决方案。
id_1 total
3    6+7+8 + 6+7+8 + 33+33+33 + 333+333+333
4    1+2+3 + 1+2+3 + 44+44+44 + 444+444+444
id_1 total
3    6+7+8 + 6+7+8 + 33/3+33/3+33/3 + 333/3+333/3+333/3
4    1+2+3 + 1+2+3 + 44/3+44/3+44/3 + 444/3+444/3+444/3