MySql选择查询 - 从WHERE子句获取错误

时间:2012-01-24 06:25:03

标签: mysql select

我是MySQL的新手。

SELECT
     receive_item.RECEIPT_ID,
     receive_item.ITEM_ID, 
     (receive_item.QTY - delivery_item.QTY) AS QtyRemained 
FROM receive_item
INNER JOIN delivery_item
ON receive_item.ITEM_ID = delivery_item.ITEM_ID 
AND receive_item.RECEIPT_ID = delivery_item.RECEIVE_ID

这是上面查询的结果

RECEIPT_ID ITEM_ID  QTYRemained
    1         1         0
    2         2         0
    3         3         1
    4         4         0
    5         5         0

我想只显示QTYRemained值不为0的行。 像这样的东西

RECEIPT_ID ITEM_ID  QTYRemained
    3         3         1

当我将“从QTYRemained!= 0”添加到上面的选择查询结尾时,出现错误。 有人可以告诉我为什么它不起作用吗?

4 个答案:

答案 0 :(得分:2)

在最后添加

WHERE QtyRemained > 0

所以...

SELECT
     receive_item.RECEIPT_ID,
     receive_item.ITEM_ID, 
     (receive_item.QTY - delivery_item.QTY) AS QtyRemained 
FROM receive_item
INNER JOIN delivery_item
ON receive_item.ITEM_ID = delivery_item.ITEM_ID 
AND receive_item.RECEIPT_ID = delivery_item.RECEIVE_ID
WHERE QtyRemained > 0

答案 1 :(得分:2)

使用having代替where

SELECT
     receive_item.RECEIPT_ID,
     receive_item.ITEM_ID, 
     (receive_item.QTY - delivery_item.QTY) AS QtyRemained 
FROM receive_item
INNER JOIN delivery_item
ON receive_item.ITEM_ID = delivery_item.ITEM_ID 
AND receive_item.RECEIPT_ID = delivery_item.RECEIVE_ID
having QtyRemained > 0

或者你可以这样做:

SELECT
     receive_item.RECEIPT_ID,
     receive_item.ITEM_ID, 
     (receive_item.QTY - delivery_item.QTY) AS QtyRemained 
FROM receive_item
INNER JOIN delivery_item
ON receive_item.ITEM_ID = delivery_item.ITEM_ID 
AND receive_item.RECEIPT_ID = delivery_item.RECEIVE_ID
where (receive_item.QTY - delivery_item.QTY) > 0

答案 2 :(得分:1)

尝试: -

SELECT
     receive_item.RECEIPT_ID,
     receive_item.ITEM_ID, 
     (receive_item.QTY - delivery_item.QTY) AS QtyRemained 
FROM receive_item
INNER JOIN delivery_item
ON receive_item.ITEM_ID = delivery_item.ITEM_ID 
AND receive_item.RECEIPT_ID = delivery_item.RECEIVE_ID
group by receive_item.RECEIPT_ID
Having QtyRemained > 0

答案 3 :(得分:1)

因为我是一个老糊涂的人并且在没有HAVING条款的情况下拒绝使用GROUP BY,这里是另一种解决方案

SELECT
     ri.RECEIPT_ID,
     ri.ITEM_ID, 
     (ri.QTY - di.QTY) AS QtyRemained 
FROM receive_item ri
INNER JOIN delivery_item di
ON ri.ITEM_ID = di.ITEM_ID 
AND ri.RECEIPT_ID = di.RECEIVE_ID
WHERE ri.QTY > di.QTY

非常简单