1

I have a product-table and a table containing all parts of a product and the quantity.

Structure of products table:

id 
name

Structure of parts table:

id
productsId
partsId
quantity

Now I want to get all products and for every product the total quantity parts and quantity of different parts . The current solution is this query:

SELECT
    products.*,
    (
        SELECT count(quantity) 
        FROM product_has_part 
        WHERE product_has_part.productsId = products.id
    ) AS partsQty,
    (
        SELECT sum(quantity) 
        FROM product_has_part 
        WHERE product_has_part.productsId = products.id
    ) AS sumQty
FROM products

Now I have to subselects across the same table. So I think there must be a better way to create this query?

2 Answers 2

1

use join

Select *,count(quantity),sum(quantity)
From products p join 
product_has_part pp on pp.productsId = p.id
FROM products

or Group by use for count or sum for each id

Select *,count(quantity),sum(quantity)
From products p join 
product_has_part pp on pp.productsId = p.id
FROM products
Group by p.id
Sign up to request clarification or add additional context in comments.

1 Comment

I forgot mysql isnt ansi, and group by p.id will work
0

p.f1, p.f2, p.f3 mean each field of p.

select p.f1, p.f2, p.f3  ... count(php.quantity), sum(php.quantity)
from products p
join product_has_part php
  on p.productsId  = php.productsId 
group by  p.f1, p.f2, p.f3 ..

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.