0

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')
0

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

SELECT sum(kilo) 
FROM `products` 
WHERE `id` IN (
    SELECT `product` 
    FROM `person` 
    WHERE `user` = '1'
);
|improve this answer|||||
2

This will solve your problem, use SUM and join in 1 query.

SELECT SUM(`kilo`) total_kilo
FROM `person` 
    INNER JOIN `products` 
    on `person`.`product` = `products`.`id`;

Or selecting/counting for user 1 alone

SELECT SUM(`kilo`) total_kilo 
FROM `person` 
    INNER JOIN `products` 
    on `person`.`product` = `products`.`id` 
WHERE `person`.`user` =1;

Or selecting/counting for every user

SELECT `person`.`user`, SUM(`kilo`) total_kilo 
FROM `person` 
    INNER JOIN `products` 
    on `person`.`product` = `products`.`id` 
GROUP BY `person`.`user`;
|improve this answer|||||

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.