选择每1个id产品类别的产品价格总和

时间:2014-12-10 09:45:56

标签: mysql sql multiple-tables

我想为我的查询问题找到解决方案。我需要找到所有priceProduct *数量的SUM并用每个productcategory分隔。我已经进行了查询,但执行它需要更长的时间。这是我的查询,

SELECT 
    pb.ProductCategoryID,
    pb.ProductCategoryDescription,
    (SELECT
        SUM((SELECT pd.HPP FROM `price details` pd WHERE pd.ProductID = pdt.ProductID ORDER BY pd.PriceDetailID DESC LIMIT 1)*
                (SELECT StockProductBallance FROM `stock product` sp WHERE sp.ProductID = pdt.ProductID ORDER BY sp.StockProductID DESC LIMIT 1))
        FROM product pdt
        WHERE pdt.ProductCategoryID = pb.ProductCategoryID
    ) AS Total
FROM `product category` pb
GROUP BY pb.ProductCategoryID

这是我的示例表

表产品:

+------+-------+
| id_p | id_pc |
+------+-------+
|    1 |     3 |
|    2 |     4 |
|    3 |     3 |
|    4 |     4 |
+------+-------+

表productcategory:

+-------+---------+
| id_pc | pc_name |
+-------+---------+
|     3 | new_pc  |
|     4 | old_pc  |
+-------+---------+

表价格详情:

+---------------+------+-----+
| PriceDetailID | id_p | hpp |
+---------------+------+-----+
|             1 |    1 | 100 |
|             2 |    1 | 110 |
|             3 |    1 | 120 |
|             4 |    2 | 200 |
|             5 |    2 | 210 |
|             6 |    2 | 220 |
+---------------+------+-----+

table stockProduct:

+-----------------+------+---------------+
| id_stockProduct | id_p | stockballance |
+-----------------+------+---------------+
|               1 |    1 |            10 |
|               2 |    1 |            11 |
|               3 |    1 |            12 |
|               4 |    2 |            20 |
|               5 |    2 |            21 |
|               6 |    2 |            22 |
+-----------------+------+---------------+

真的需要你帮助的人,以便更好地查询..

0 个答案:

没有答案