获得最便宜的产品价格

时间:2018-06-15 18:41:22

标签: mysql join select distinct

我有两张表:productsprices

products

  • id(PK)
  • 名称

prices

  • id(PK)
  • product_id(FK>产品)
  • originalPrice

每种产品可能有多种价格。我想要实现的是一个返回all products on-sale with its cheapest price的查询。

  • on-sale =价格< originalPrice
  • 如果产品 on-sale,则不应将其包含在结果中
  • 如果某个产品的多个价格符合on-sale的价格,则只返回最便宜的价格。

结果表应包含这些列

  • products.id
  • products.name
  • prices.id
  • prices.price
  • prices.originalPrice

根据我的尝试,我最终会遇到此问题:#1055 - Expression #3 of SELECT list is not in GROUP BY clause and contains nonaggregated column 'tbl.price' which is not functionally dependent on columns in GROUP BY clause; this is incompatible with sql_mode=only_full_group_by请注意,我无法更改配置。

MySQL版本: 5.7.22

我已在此处上传了包含示例数据的SQL导出: https://www.dropbox.com/s/6ucdv6592dum6n6/stackoverflow_export.sql?dl=0

4 个答案:

答案 0 :(得分:2)

select pro.name, MIN(pri.price) from products pro
inner join price pri on pri.product_id = pro.id 
where pri.price < pri.originalPrice 
group by pro.name

没有任何数据的注射:p可能需要稍微调整

答案 1 :(得分:1)

希望这适合你

SELECT *,MIN(price)  FROM (
SELECT name, products.id,price
FROM products
INNER JOIN productItems
   ON products.id = productItems.productId
WHERE price < originalPrice
ORDER BY (price-originalPrice)
) as tbl GROUP BY id;

OR

SELECT *,MIN(diff)  FROM (
SELECT name, products.id,price,(price-originalPrice) as "diff"
FROM products
INNER JOIN productItems
   ON products.id = productItems.productId
WHERE price < originalPrice
ORDER BY products.id,(price-originalPrice)
) as tbl GROUP BY id;

答案 2 :(得分:1)

试试这个:

SELECT * 
FROM `products` pro
JOIN price pri on pri.productId = pro.id
WHERE pri.price < pri.originalPrice
AND pri.price = 
( 
    SELECT min(p.price) 
    FROM price p 
    WHERE p.productId = pro.id AND p.price < p.originalPrice 
)

答案 3 :(得分:1)

这适用于您提供的保管箱链接:http://sqlfiddle.com/#!9/a6306d/3

 select pro.name, MIN(pri.price) from products pro
    inner join price pri on pri.productId = pro.id 
    where pri.price < pri.originalPrice 
    group by pro.name