选择数据库中每种产品的MIN / MAX价格。
我只能获得具有指定标识符的产品。
我正在使用 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
,maxProductPrice
和productName
。
感谢您的帮助。上面的两个答案都是正确的 - 但我选择了@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`
干杯!
答案 0 :(得分: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`
答案 1 :(得分:3)
首先,当你使用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
因为您只选择一种产品,所以可能不需要group 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`
这将返回所有产品的信息。