0

My data in table_1 and table_2.

table_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

table_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

I only know how to do what I want with two steps:

First LEFT JOIN to get:

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

Then LEFT JOIN with table_1 again to 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

Can I do it in only one SQL?

JERRY-the chuha
  • 592
  • 1
  • 4
  • 16
Sunry
  • 602
  • 4
  • 11

2 Answers2

1

Here is the SQLFIddel Demo

Below is the Query which You can try

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;
Romesh
  • 2,291
  • 3
  • 24
  • 47
0

Got inspiration from: How to count items in comma separated list MySQL

SELECT t1.id_1,
  SUM(t1.num / (LENGTH(t1.ids_2) - LENGTH(REPLACE(t1.ids_2, ',', '')) + 1) + t2.num)
    AS total
  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;

If no above division, the result would be:

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

With the division, the result would be what I want:

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
Community
  • 1
  • 1
Sunry
  • 602
  • 4
  • 11