Reputation: 63
Yes yes, I know. The title is stupid and hard to understand.
Question:
There's a DB1
and a DB2
.
DB1
has column
s called id
and price
. id
is a unique number for each item like 301
and so on. There's only one of each id
in this DB
.
DB2
contains a column named id
and one named price
. This DB has the duty of collecting data about each id
( item ) via a php
script.
This means multiple rows with the same unique id
.
a picture to demonstrate:
What i'm trying to do:
a script that querys an id
( matches the id with another table ) and sum
s up all the price
columns with the same id
.
I understand innerjoin
SELECT db1.id, db2.price
FROM db1
INNER JOIN db2
ON db1.id=db2.id;
but I want to sum
all db2.price
rows before showing. What can I do?
Upvotes: 2
Views: 56
Reputation: 8607
What you want is this:
(I guess you want to show db1.price too (or other fields from db1, otherwise there is no meaning have this join)
SELECT db1.id, db1.price, db2s.price -- rest of db1 fields here
FROM db1
INNER JOIN (select id, sum(price) price from db2 group by id) as db2s
ON db1.id=db2s.id;
Upvotes: 1
Reputation: 40919
I don't think you need a join for that. It should be enough to just do:
SELECT id, sum(price) as price_sum FROM db2 GROUP BY id
This should give you 2 columns:
Upvotes: 0