mysql 中的同一个 table 的多个子选择

Multiple Subselects to same table in mysql

我有一个产品-table 和一个包含产品所有部分和数量的 table。

产品结构table:

id 
name

零件结构table:

id
productsId
partsId
quantity

现在我想获取所有产品以及每个产品的零件总数和不同零件的数量。当前的解决方案是这个查询:

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

现在我必须在同一个 table 中进行子选择。所以我认为一定有更好的方法来创建这个查询?

使用加入

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

Group by用于每个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

p.f1,p.f2,p.f3表示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 ..