在mysql中同时插入和更新

时间:2013-07-11 18:54:23

标签: mysql function sum

我想在mysql中同时插入和更新两个表。我有表和下面的详细信息

CREATE TABLE Info
(
 id int auto_increment primary key, 
 BBP decimal(19,2) default "0.00" 

);


create table bill(Amount_paid decimal(19,2) default "0.00",
BAP decimal(19,2) default "0.00"
);    


INSERT INTO Info(BBP)
 VALUES
('30');


INSERT INTO bill(bid,Amount_paid,BAP)
SELECT i.id,
   10,
   i.BBP -
(SELECT COALESCE(sum(b.AMOUNT_PAID),0)+10
FROM bill b
WHERE bid = i.id)
 FROM info i
WHERE i.id = 1;

update info set BBP = (select BBP - coalesce(sum(Amount_paid),0) from bill WHERE id=1);

基本上,在插入Amount_paid之后,BBP预计会更新,但它只在第一次插入Amount_paid时正确更新,在第二次和其他插入后不正确。 每个东西都按照安排工作,但更新查询不能按预期工作。请希望有人教我更新查询的错误或更好的查询。谢谢你的帮助

1 个答案:

答案 0 :(得分:0)

你试过

吗?
update info set BBP = BBP - (select coalesce(sum(Amount_paid),0) from bill) WHERE id=1;