【问题标题】:Get cheapest price for a product获得产品的最便宜价格
【发布时间】:2018-06-15 18:41:22
【问题描述】:

我有两张桌子:productsprices

products

  • id (PK)
  • 姓名

prices

  • id (PK)
  • product_id(FK > 产品)
  • 价格
  • 原价

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

  • on-sale = 价格
  • 如果产品不是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

【问题讨论】:

标签: mysql join select distinct


【解决方案1】:
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 可能需要稍作调整

【讨论】:

  • 您的聚合函数将返回最顶部的分组行而不是最便宜的行
【解决方案2】:

试试这个:

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】:

希望这对你有用

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;

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;

【讨论】:

  • 我之前尝试过类似的方法。不幸的是,我最终得到:#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,我无法更改配置)
  • 表示GROUP BYaggregation功能一起使用时不能使用其他字段。在这种情况下,您需要在应用程序端处理这些值。
  • 有一些技巧但不能使用最新的 MySql stackoverflow.com/a/36033983/8179245
  • 谢谢!我已经更新了我的问题.. 不幸的是我无法更新配置。
【解决方案4】:

这适用于您提供的保管箱链接: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

【讨论】:

  • 希望对您有所帮助!干杯:)
  • 谢谢!我已经更新了我的问题。不幸的是,我需要在结果表中提供更多信息(例如price.id)。很酷的工具(sqlfiddle)!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-09-30
  • 1970-01-01
  • 2015-01-22
  • 2017-06-04
相关资源
最近更新 更多