1

我有一个运输计算器的查询,它应该根据重量和国家/地区等几个标准从数据库中选择最低值。该查询旨在获取一个或多个与条件匹配的 ShippingProviderId 的第一个最低值。

问题是 group by 查询混合了 ShippingCost 表中的几行的结果,并抛出了异常。我需要 Price 和 ShippingCostId 来自同一行。我怎样才能防止这种结果混合?也许 Group By 不是我需要的?

SELECT MIN(s1.Price), s1.ShippingCostId, s1.Weight, s2.CoD, s2.Artnr, s2.CoD, 
s2.Regular, s2.ShippingProviderId, s3.ProviderName FROM ShippingCost s1

INNER JOIN ShippingProvider s2 ON s1.ShippingProviderId = s2.ShippingProviderId 
INNER JOIN ShippingProviderTranslations s3 ON (s2.ShippingProviderId = s3.ShippingProviderId AND s3.Language = 'xx') 

WHERE CountryId = 123 AND (Weight >= 0.5 AND Weight <= 50) AND s2.Regular = 0

GROUP BY s2.ShippingProviderId

如果我删除 MIN() 表达式,则行不再混合,但最低值不是找到的,因为最低值它具有更高的 ShippingCostId 并且稍后添加(是主键)。为权重添加 MIN() 表达式或尝试按权重排序也不起作用。我尝试了很多不同的方法,但我感到很难过。

有什么建议么?

4

1 回答 1

1

您应该在最低价格上使用连接,而不是选择不按列分组

SELECT t1.min_price, s1.ShippingCostId, s1.Weight, s2.CoD, s2.Artnr, s2.CoD, 
s2.Regular, s2.ShippingProviderId, s3.ProviderName 

FROM ShippingCost s1

INNER JOIN ShippingProvider s2 ON s1.ShippingProviderId = s2.ShippingProviderId 
INNER JOIN ShippingProviderTranslations s3 ON (s2.ShippingProviderId = s3.ShippingProviderId AND s3.Language = 'xx') 
INNER JOIN (
  select MIN(s1.Price) as min_price, s2.ShippingProviderId
  from FROM ShippingCost s1 
  INNER JOIN ShippingProvider s2 ON s1.ShippingProviderId = s2.ShippingProviderId 
  group by s2.ShippingProviderId
) t1 on t1.ShippingProviderId = s2.ShippingProviderId and s1.Price= t1.min_price

使用 select for not gruoped by columns with aggregation function 会产生不可预测的结果
,这种习惯在 SQL 中已被弃用,在最新版本的 mysql 中不允许并产生错误

于 2018-05-25T11:50:43.233 回答