我正在尝试为两个表中的某些完整性编写一些查询。查询是这样的
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
不是列。
答案 0 :(得分: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
答案 1 :(得分: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
答案 2 :(得分:4)
WHERE
出现在SELECT
之前。
所以你需要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