Harsh Nagalla
Harsh Nagalla

Reputation: 1245

How to count the rows from multiple tables in MYSQL and get a sum of it?

I have 3 tables

  1. Table 1 - table1_id, title
  2. Table 2 - table2_id, table1_id
  3. Table 3 - table3_id, table2_id

Here Table 2 has reference of Table 1 there can be multiple Table 2 rows referring Table 1 and Table 3 is referring to Table 2 there can be multiple Table 3 rows referring to Table 2.

There is an one-many relationship between Table1-Table2 and Table2-Table3

Now I want the sum of all the rows in Table 3 with table1_id

enter image description here

Input- table1_id = "abc"

Output- 9

PS- Sorry for such abstract description , its quite difficult to explain here if needed I can add some more details.

Upvotes: 0

Views: 37

Answers (1)

Andreas
Andreas

Reputation: 506

SELECT t1.id, COUNT(t3.id), SUM(t3.amount)
  FROM table1 t1
  JOIN table2 t2 ON t1.id = t2.table1_id
  JOIN table3 t3 ON t2.id = t3.table2_id
 GROUP BY t1.id

Upvotes: 1

Related Questions