mandza
mandza

Reputation: 330

Left Join don't list multiple rows

I have problem listing multiple rows from two tables. I had make research but I didn't find solution that fit my needs. Multiple use of LEFT JOIN brings only 1 row this is problem similar to mine. How can an SQL query return data from multiple tables also did not help me :)

This is what I have and what I want. I have two table, for example; Products and Amounts.

product -> id - name
amount  -> id - pid - color - amount

product -> 1  - Book
           2  - Door
           3  - Table
amount  -> 1  - 1 - red - 5
           2  - 1 - blue- 10
           3  - 3 - green - 3

This is query I run with no problem:

SELECT product.id AS pid, 
product.name AS pname, 
sum(amount.amount) AS amnt 
FROM product 
LEFT JOIN amount ON product.id=amount.pid 
WHERE product.id='1'

And this is query I had problem with:

SELECT product.id AS pid, 
product.name AS pname, 
sum(amount.amount) AS amnt 
FROM product LEFT JOIN amount ON product.id=amount.pid 
WHERE product.name LIKE '%o%'

The second query list only one row, but I expect this result:

row1: 1 - Book - 15
row2: 2 - Door - null

Upvotes: 0

Views: 152

Answers (1)

Olli
Olli

Reputation: 1738

Try using group by as :

SELECT product.id AS pid, product.name AS pname, sum(amount.amount) AS amnt FROM product LEFT JOIN amount ON product.id=amount.pid WHERE product.name LIKE '%o%' GROUP BY product.id

reason: Since sum() is an aggregate function it needs to know what elements to sum up for you. otherwise it will sum all up into one value (which you got).

See group by modifiers in the manual about details.

Upvotes: 6

Related Questions