获得最便宜的产品价格

f4t66c6m  于 2021-06-20  发布在  Mysql
关注(0)|答案(4)|浏览(307)

我有两张table: products 以及
prices products id(主键)
名称 prices id(主键)
产品id(fk>产品)
价格
原始价格
每种产品可能有多种价格。我想要实现的是返回我的查询 all products on-sale with its cheapest price . on-sale =价格<原价
如果产品不是 on-sale ,不应包含在结果中
如果一个产品有多个价格符合 on-sale ,只返回最便宜的价格。
结果表应该有以下列
产品id
产品名称
价格.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
我上传了一个sql导出的示例数据here:https://www.dropbox.com/s/6ucdv6592dum6n6/stackoverflow_export.sql?dl=0

yjghlzjz

yjghlzjz1#

希望这对你有用

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;
hmae6n7t

hmae6n7t2#

试试这个:

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 
)
cnwbcb6i

cnwbcb6i3#

这适用于您提供的dropbox链接: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
e5nszbig

e5nszbig4#

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可能需要稍微调整一下

相关问题