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?