9

我正在尝试为两个表的完整性编写一些查询。查询是这样的

SELECT if( o.is_discounted !=1, o.item_cost, o.discounted_item_cost ) AS order_item_total,
SUM( oi.quantity * oi.price ) AS item_total
FROM orders o
INNER JOIN order_items oi ON oi.order_id = o.id
WHERE order_item_total != item_total
GROUP BY o.id

我过去肯定使用过此类列的别名,所以我不确定为什么在这种情况下它告诉我order_item_total不是列。

4

3 回答 3

8

在聚合列上使用具有。

SELECT if(o.is_discounted != 1, o.item_cost, o.discounted_item_cost) order_item_total,
  SUM(oi.quantity * oi.price) item_total
FROM orders o
INNER JOIN order_items oi ON oi.order_id = o.id
GROUP BY o.id
HAVING order_item_total != item_total
于 2012-04-16T16:50:19.503 回答
4

尝试将整个事情包装在另一个SELECT查询中。

SELECT *
FROM 
(
    SELECT if( o.is_discounted !=1, o.item_cost, o.discounted_item_cost ) AS order_item_total,
    SUM( oi.quantity * oi.price ) AS item_total
    FROM orders o
    INNER JOIN order_items oi ON oi.order_id = o.id
    GROUP BY o.id
) x
WHERE X.order_item_total != X.item_total
于 2012-04-16T16:47:14.013 回答
4

WHERESELECT在处理数据时出现在前面。所以你需要WHERE if( o.is_discounted !=1, o.item_cost, o.discounted_item_cost ) != SUM( oi.quantity * oi.price )

处理此问题的另一种方法是使用子查询

SELECT 
  ..
 FROM 
   ( //your query here
   ) t
//now you can use your aliases
WHERE t.order_item_total != t.item_total

这里有:

SELECT if( o.is_discounted !=1, o.item_cost, o.discounted_item_cost ) AS order_item_total,
SUM( oi.quantity * oi.price ) AS item_total
FROM orders o
INNER JOIN order_items oi ON oi.order_id = o.id
WHERE 1
GROUP BY o.id
HAVING order_item_total != item_total
于 2012-04-16T16:47:51.983 回答