获得多对多的最高/最低价值

时间:2016-03-09 02:17:04

标签: sql

我有3张表,deep_mergeProduct(ID, Name, Price)Category(ID, Name)

我通过Product_Category在Product和Category之间建立了很多关系。但是,我想显示每个类别的最低/最高价格,这是我得到了多远:

Product_Category(ProductID, CategoryID)

我希望每个类别的最便宜和最昂贵的产品的价格按类别分组,如下所示:

SELECT 
(SELECT MIN(Product.Price) FROM Product) AS 'Lowest price', 
(SELECT MAX(Product.Price) FROM Product) AS 'Highest price', 
Category.Name AS CategoryName

FROM Product_Category 
JOIN Product ON Product_Category.ProductID = Product.ID 
JOIN Category ON Product_Category.CategoryID = Category.ID
GROUP BY Category.Name

1 个答案:

答案 0 :(得分:2)

不需要子查询:

SELECT 
    MIN(Product.Price) AS 'Lowest price', 
    MAX(Product.Price) AS 'Highest price', 
    Category.Name AS CategoryName
FROM Product_Category 
    JOIN Product ON Product_Category.ProductID = Product.ID 
    JOIN Category ON Product_Category.CategoryID = Category.ID
GROUP BY Category.Name