从不同的表中减去两个字段并更新MySQL中前一个字段中的值

时间:2014-01-31 09:05:10

标签: java mysql sql mysql-workbench

我有两个表:Item_detail(P_name,Available)和Customer_detail(P_name,Quantity)

现在我想从“可用”字段中减去“数量”字段,然后想要在“可用”字段中设置减去的值。我写这段代码,但它无法正常工作

update Item_detail  
    set Available=(
        select (A.Available-B.Quantity) as Available 
            from Item_detail as A 
            join (select Quantity from Customer_detail  where P_name='ipod') as B 
            where  A.P_name='ipod') ;   

请帮助!!

2 个答案:

答案 0 :(得分:1)

UPDATE Item_detail JOIN Customer_detail USING (P_name)
SET    Item_detail.Available = Item_detail.Available - Customer_detail.Quantity
WHERE  P_name='ipod'

答案 1 :(得分:1)

希望这会对你有所帮助

UPDATE Item_detail A
JOIN (SELECT Quantity FROM Customer_detail  WHERE P_name='ipod') AS B    
SET Available=A.Available-B.Quantity
WHERE A.P_name='ipod';