结合SUM和WHERE - 没有得到我期望的结果

时间:2012-02-22 18:24:54

标签: mysql sql

SELECT shop.price,shop.item,shop.full_item_name,shop.qty,shop.shop_id,
SUM( averages_20128.combined_prices + averages_20127.combined_prices ) AS combined,
SUM( averages_20128.total_sales + averages_20127.total_sales ) AS total
FROM `shop`
JOIN `averages_20128`
ON averages_20128.full_item_name=shop.full_item_name
JOIN `averages_20127`
ON averages_20128.full_item_name=averages_20127.full_item_name
JOIN `theShops`
ON theShops.id=shop.shop_id
WHERE shop.price<combined/total
AND theShops.open='1'
AND shop.id!=''
AND `total`>10
ORDER BY combined/total DESC
LIMIT 100

错误:'where子句'

中的未知列'合并'

概述:我考虑创建一个存储当前平均值和排序的列,但是当我第一次启动并且现在有大量数据时我没有这样做。我宁愿不经历这一切并重新计算。所以我希望MySQL可以为我做数学。

当我省略WHERE / ORDER子句时,这确实有效,这让我相信我的语法有问题。

4 个答案:

答案 0 :(得分:1)

变化:

WHERE shop.price < combined/total

要:

WHERE shop.price <
  SUM(averages_20128.combined_prices + averages_20127.combined_prices)/total

或将其移至HAVING子句:

HAVING shop.price < combined/total

WHERESUM()之前应用,因此聚合列尚不可用。 HAVING几乎持续发生。

答案 1 :(得分:0)

combined/total使用结果集中的列,而不是原始数据中的列。

为了像这样引用它们,您需要重现创建它们的计算,或者使用子查询进行计算,然后在外部查询中进行过滤和排序。

答案 2 :(得分:0)

要使用SUM,您需要在某处GROUP BY

答案 3 :(得分:0)

正如其他人所说,它不起作用,因为combined条款中没有where

SQL中的执行顺序如下:

FROM clause
WHERE clause
GROUP BY clause
HAVING clause
SELECT clause
ORDER BY clause

因此select中未定义您在where中定义的名称 - 此外,sum等聚合仅在Group By执行后才可用。

我想要的猜测实际上是这样的

SELECT shop.price,shop.item,shop.full_item_name,shop.qty,shop.shop_id, 
combined, total
FROM `shop`
JOIN (
    SELECT averages_20128.full_item_name, 
    SUM(averages_20128.combined_prices + averages_20127.combined_prices) AS combined,
        SUM( averages_20128.total_sales + averages_20127.total_sales ) AS total
    FROM `averages_20127` JOIN averages_20128
        ON averages_20128.full_item_name=averages_20127.full_item_name
    GROUP BY averages_20128.full_item_name
) AS averages
ON averages.full_item_name=shop.full_item_name
JOIN `theShops`
ON theShops.id=shop.shop_id
WHERE shop.price<combined/total
AND theShops.open='1'
AND shop.id!=''
AND `total`>10
ORDER BY combined/total DESC
LIMIT 100

totalcombined的值在子选择中计算,然后与当前商店价格进行比较。

同样,它并不完全清楚你想做什么,所以这可能不是你需要的。