OK, my head hurts...!
This beautiful MySQL query:
(SELECT mtwitterfollowers AS twitfollow FROM `media` WHERE media.id=1)
UNION
(SELECT SUM(twitterfollowers) AS twitfollow FROM people LEFT JOIN peoplejoin ON peoplejoin.people_id = people.id LEFT JOIN positions ON position_id = positions.id WHERE peoplejoin.media_id = 1)
UNION
(SELECT SUM(twitterfollowers) AS twitfollow FROM people LEFT JOIN peoplejoin ON peoplejoin.people_id = people.id LEFT JOIN networkjoin ON networkjoin.network_id = peoplejoin.network_id LEFT JOIN positions ON position_id = positions.id WHERE networkjoin.media_id = 1)
...returns three rows of pretty numbers.
Ideally, I'd like this query to return all three "twitfollow" results, SUMmed together.
However, putting a SUM round them gives me an error about "every derived table must have its own alias", and I'm a little confused as to quite how to do solve that.
(Of course, I could just sum the results in PHP; but I am assuming that it's quicker to do this using the MySQL server. Would I be right?)
You can use the SUM() function in a SELECT with JOIN clause to calculate the sum of values in a table based on a condition specified by the values in another table.
The MySQL UNION operator is used to combine the result sets of 2 or more SELECT statements. It removes duplicate rows between the various SELECT statements. Each SELECT statement within the UNION operator must have the same number of fields in the result sets with similar data types.
MySQL Union is an operator that allows us to combine two or more results from multiple SELECT queries into a single result set. It comes with a default feature that removes the duplicate rows from the result set.
Basic rules for combining two or more queries using UNIONnumber of columns and order of columns of all queries must be same. 2.) the data types of the columns on involving table in each query must be same or compatible.
Use your entire query as the FROM
clause of another query:
SELECT SUM(twitfollow) FROM (
(SELECT mtwitterfollowers AS twitfollow FROM `media` WHERE media.id=1)
UNION ALL
(SELECT SUM(twitterfollowers) AS twitfollow FROM people LEFT JOIN peoplejoin ON peoplejoin.people_id = people.id LEFT JOIN positions ON position_id = positions.id WHERE peoplejoin.media_id = 1)
UNION ALL
(SELECT SUM(twitterfollowers) AS twitfollow FROM people LEFT JOIN peoplejoin ON peoplejoin.people_id = people.id LEFT JOIN networkjoin ON networkjoin.network_id = peoplejoin.network_id LEFT JOIN positions ON position_id = positions.id WHERE networkjoin.media_id = 1)
) t1
I also changed your UNION
to UNION ALL
as you probably don't want to remove rows just because the sum from one table is equal to the sum from another table.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With