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?
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-х таблиц Source: https://ru.stackoverflow.com/questions/826252/
All Articles
union alland sum up - teran