MySQL SUM Query

Greetings, I have a query that I am struggling with, this is the first time I encounter this type of query. I have two tables as shown below.

xid is the primary key in parent_tbl1, and xid is the foreign key in child_tbl2

parent_tbl1

xid pub 
1    1    
2    1    
3    0    
4    1

child_tbl2

id ttype fno xid  qnty
1  A       0    1    0
2  A       1    1    3
3  B       1    1    4
4  A       1    2    1  
5  A       1    3    2
6  A       1    4    3
7  A       1    4    1
8  A       1    1    1

The following is an instanceization of the request in parts, which then will have to compose the entire request.

I need qnty SUM in child_tbl2:

1) Who is the parent pub '1' Therefore id 5 is excluded from child_tbl2, this is due to the fact that xid 3 is 0 in parent_tbl1

Results: child_tbl2

id ttype fno xid qnty
1  A       0    1    0
2  A       1    1    3
3  B       1    1    4
4  A       1    2    1
6  A       1    4    3
7  A       1    4    1
8  A       1    1    1

2) And which parent table has ttype 'A' in the child table. Therefore, id 3 is excluded from existing results, since id 3 ttype is B

Results: child_tbl2

id ttype fno xid qnty
1  A       0    1    0
2  A       1    1    3
4  A       1    2    1
6  A       1    4    3
7  A       1    4    1
8  A       1    1    1

3) "0", fno child_tbl2 , id 4, 6 7 , , 0 fno, 0 xid 1 fno

: child_tbl2

id ttype fno xid qnty
1  A       0    1    0
2  A       1    1    3
8  A       1    1    1

4

, .

SELECT sum(child_tbl2.qnty), parent_tbl1.xid, parent_tbl1.pub, child_tbl2.ttype, child_tbl2.fno, child_tbl2.xid 
FROM parent_tbl1, child_tbl2
WHERE parent_tbl1.xid = child_tbl2.xid
AND parent_tbl1.pub = '1'
AND child_tbl2.ttype = 'A'

AND child_tbl2.fno ? 

, , dbms (MySQL), , Zero fno. "AND child_tbl2.fno = '0", , fno 0. , , fno, SUM qnty xid

+3
1
SELECT SUM(DISTINCT src.qnty) as qnty
FROM tbl2 AS src
INNER JOIN tbl1 AS pub
  ON src.xid=pub.xid
INNER JOIN tbl2 AS fno
  ON pub.xid=fno.xid
WHERE pub.pub=1
  AND src.ttype='A'
  AND fno.fno=0
+2

Source: https://habr.com/ru/post/1764141/


All Articles