MySQL – How to Count Values of a Column

countMySQL

I've got two database tables:

Persons
id   user   product
1     1       3
2     1       5
3     1       7

products
id   kilo
3     8
5     15
7     3

I'm wondering how to count values from a database, in this case I want to get the total kilo's of products for user 1. The result should be '26'. Is this possible?

SELECT kilo FROM `products` WHERE `id` IN (SELECT `product` FROM `person` WHERE `user` = '1')

Best Answer

Put kilo inside the sum() function, like so:

SELECT sum(kilo) 
FROM `products` 
WHERE `id` IN (
    SELECT `product` 
    FROM `person` 
    WHERE `user` = '1'
);