3

目标

选择数据库中每个产品的最低/最高价格。

问题

我只能获得具有指定标识符的产品。

我有的

我正在使用MySQL,我有以下查询:

SELECT (MIN(`map`.`Product_Price`)) as `minProductPrice`,
    (MAX(`map`.`Product_Price`)) as `maxProductPrice`,
    `pr`.`Product_Name` as `productName`
FROM `bm_market_products` as `map`
JOIN `bm_products` as `pr`
JOIN `bm_markets` as `ma`
WHERE `map`.`Product_Id` = 1
AND `map`.`Product_Id` = `pr`.`Product_Id`

我的回报是minProductPrice,maxProductPriceproductName

解决方案

谢谢你的帮助。上面的两个答案都是正确的——但我选择了@GordonLinoff 的答案,因为我认为它对初学者更有用和更喜欢——但真的感谢你们俩。最终查询:

SELECT MIN(`map`.`Product_Price`) as `minProductPrice`,
       MAX(`map`.`Product_Price`) as `maxProductPrice`,
       `pr`.`Product_Name` as `productName`
FROM `bm_market_products` `map` join
     `bm_products` as `pr`
     on map`.`Product_Id` = `pr`.`Product_Id`
group by `map`.`Product_Id`

干杯!

4

2 回答 2

4
SELECT (MIN(`map`.`Product_Price`)) as `minProductPrice`,
    (MAX(`map`.`Product_Price`)) as `maxProductPrice`,
    `pr`.`Product_Name` as `productName`,
    `map`.`Product_Id` 
FROM `bm_market_products` as `map`
JOIN `bm_products` as `pr`
JOIN `bm_markets` as `ma`
WHERE `map`.`Product_Id` = `pr`.`Product_Id`
GROUP BY `map`.`Product_Id` 
于 2013-06-10T13:52:20.037 回答
4

首先,当你使用 时join,你应该总是有一个on子句,即使 MySQL 不需要这个。如果你想要一个cross join,那么就明确一点。

其次,您在查询中根本不使用该tm_markets表。不需要,所以删除它。

结果查询应该可以工作:

SELECT MIN(`map`.`Product_Price`) as `minProductPrice`,
       MAX(`map`.`Product_Price`) as `maxProductPrice`,
       `pr`.`Product_Name` as `productName`
FROM `bm_market_products` `map` join
     `bm_products` as `pr`
     on map`.`Product_Id` = `pr`.`Product_Id`
WHERE `map`.`Product_Id` = 1 

因为您只选择一种产品,所以 agroup by可能不是必需的。但是,您可能会考虑这一点:

SELECT MIN(`map`.`Product_Price`) as `minProductPrice`,
       MAX(`map`.`Product_Price`) as `maxProductPrice`,
       `pr`.`Product_Name` as `productName`
FROM `bm_market_products` `map` join
     `bm_products` as `pr`
     on map`.`Product_Id` = `pr`.`Product_Id`
group by `map`.`Product_Id`

这将返回所有产品的信息。

于 2013-06-10T13:52:46.973 回答