There are four tables, each of them has fields called price (the value of which needs to be summarized). I make a report, you need to summarize the fields of these four tables.

You need the sum of all the price fields. How do I do this?

  • one
    union all and sum up - teran
  • or sum of summation subqueries - teran
  • And if the table is MyISAM, you can build a MERGE table. - Akina
  • one
    @Akina I like it when a beginner is advised by what not every advanced person will do. Zolushka, how do you connect the tables? - Total Pusher
  • @TotalPusher The fact that he is new does not mean that he is an idiot. And what is the MyISAM Engine, and how to use the MERGE Engine, it is fully written in the documentation. - Akina

2 answers 2

As the easiest way, so to say in the forehead, is to use UNION ALL and in one query with a subquery to get one digit:

 SELECT SUM(`sum`) AS `total` FROM ( (SELECT SUM(`price`) AS `sum` FROM `table_first`) UNION ALL (SELECT SUM(`price`) AS `sum` FROM `table_second`) UNION ALL (SELECT SUM(`price`) AS `sum` FROM `table_third`) UNION ALL (SELECT SUM(`price`) AS `sum` FROM `table_last`) ) AS `all_tables`; 

I don’t know how many records you have and how fast this query will fly, perhaps it will be better to execute 4 separate simple queries to each table and then summarize in PHP.

    Everything is very simple. Here is the simplest query:

     SELECT SUM(table1.price) AS sumPrice1, SUM(table2.price) AS sumPrice2, SUM(table3.price) AS sumPrice3, SUM(table4.price) AS sumPrice4 FROM table1, table2, table3, table4 LIMIT 1 

    Then PHP gets the sum of the columns of each table and adds:

     $resSum = $row['sumPrice1'] + $row['sumPrice2'] + $row['sumPrice3'] + $row['sumPrice4']; echo $resSum; // сумма всех столбцов 4-х таблиц 
    • Why is there a limit? - korytoff