我有一个运输计算器的查询,该计算器应该根据几个标准(如重量和国家/地区)从数据库中选择最低值。该查询旨在获得符合条件的一个或多个ShippingProviderIds的第一个最低值。
问题是group by query混合了来自ShippingCost表的几行的结果,并将hings抛出了whack。我需要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()表达式,或尝试按重量排序。我尝试了很多不同的方法,但我感到难过。
有什么建议吗?
答案 0 :(得分: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而不是具有聚合功能的列的gruoped会产生不可预测的结果
这种习惯在SQL中被弃用,在最新版本的mysql中不允许并产生错误