SUM from multiple tables

Questions about the MySQL, PostgreSQL, and most other databases, as well as using it with PHP can be asked here.

Moderator: General Moderators

Post Reply
User avatar
bluesman333
Forum Commoner
Posts: 52
Joined: Wed Dec 31, 2003 9:47 am

SUM from multiple tables

Post by bluesman333 »

I want to select a sum of values...but from multiple tables.

Code: Select all

$sql = "
SELECT SUM(a.sales_type1), SUM(b.sales_type2)
FROM type1 AS a, type2 AS b
WHERE a.id = b.id";
The problem I am having is that there is a different number of rows in each table and the JOIN is adding rows to the other table

I also need to add a customer table to this statement and GROUP BY the customer number or customer state
Last edited by bluesman333 on Wed Sep 06, 2006 6:03 pm, edited 1 time in total.
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post by feyd »

SQL is not PHP. :roll:
User avatar
wtf
Forum Contributor
Posts: 331
Joined: Thu Nov 03, 2005 5:27 pm

Post by wtf »

What version of mysql do you use?

You could create a UNION

you could do something like this

create view sumofall as
select salestype from a
union
select salestype from b
union
select salestype from c


then

select sum(salestype) from sumofall

I'm sure it could also be done with some subqueries
Post Reply