用于扣除股票的更新查询中的MySQL子查询选择语句

时间:2012-11-21 08:06:26

标签: mysql

我有两张桌子

table_inventory:

item_no
item_name
item_qty

table_pos:

orderno
qty

我想将购买的商品(数量)扣除到库存商品(item_qty)。所以我可以直接更新table_inventory

UPDATE table_inventory 
SET item_qty = (item_qty - (SELECT qty FROM tblpos WHERE qty='" & txtqty.Text & "'))
WHERE item_no='" & txtitemno.Text & "'

我似乎猜对了,但每当我尝试两次相同的项目时。我会得到“子查询返回超过1行”

3 个答案:

答案 0 :(得分:0)

怎么样?:

UPDATE table_inventory 
SET 
    item_qty = (item_qty - (SELECT qty FROM tblpos WHERE qty='" & txtqty.Text & "' LIMIT 0,1)) 
WHERE item_no='" & txtitemno.Text & "'

你真的应该sqlfiddle,这样人们可以更好地帮助你。

答案 1 :(得分:0)

首先,该查询看起来很可疑 - 从用户指定的qty值的表中选择qty。

为什么不直接在txtqty.Text中使用用户输入?

其次,正如错误所示,SELECT返回具有相同qty值的多行。如果这是您的查询将是什么,您只需添加DISTINCT子句以获得一行一行。

UPDATE table_inventory 
SET 
    item_qty = 
        (item_qty - (
                     SELECT DISTINCT qty 
                     FROM tblpos 
                     WHERE qty='" & txtqty.Text & "'
                     )
        )
WHERE item_no='" & txtitemno.Text & "'

或者简单地说,只需使用用户输入本身。

此外,您的查询构造很容易进行SQL注入,因为您只是在阅读用户输入并将其附加到查询中而不对其进行清理。你也应该照顾好。

答案 2 :(得分:0)

我认为在扣除之前你需要sum的数量,所以我的建议如下,

UPDATE table_inventory 
SET item_qty = 
(item_qty - (SELECT sum(qty) FROM tblpos WHERE qty='" & txtqty.Text & "' group by qty))
WHERE item_no='" & txtitemno.Text & "'
相关问题