使用insert和select在表中返回null

时间:2013-07-11 10:38:15

标签: mysql function sum

我想选择数据,从数据总和中减去数据并将其插入到一个查询中的不同表中,但它总是在表中返回null。要说清楚,下面是我的查询

insert 
    into bill(Amount_paid,BAP) 
select 
    '10',Info.BBP - COALESCE(SUM(bill.Amount_paid),0) 
from 
    Info,bill 
where 
    info.id='1';

| ID | BBP |

| 1 | 20 |

| BID | AMOUNT_PAID | BAP |

| 1 | 10 | (null)|

请问我该如何处理这种情况,我已经尽力做到这一点,但无济于事,任何关于如何解决这个问题的想法都将受到赞赏。

2 个答案:

答案 0 :(得分:0)

另见此链接: http://dev.mysql.com/doc/refman/5.1/en/insert-select.html

规格说

 The target table of the INSERT statement may appear in the FROM clause of the SELECT 
part of the query. (This was not possible in some older versions of MySQL.) However, 
you cannot insert into a table and select from the same table in a subquery.


When selecting from and inserting into a table at the same time, MySQL creates a 
temporary table to hold the rows from the SELECT and then inserts those rows into the 
target table. However, it remains true that you cannot use INSERT INTO t ... SELECT ...
FROM t when t is a TEMPORARY table, because TEMPORARY tables cannot be referred to 
twice in the same statement (see Section C.5.7.2, “TEMPORARY Table Problems”). 

所以就此而言。您正在从内部查询中的表格中选择,并尝试在同一个表中插入相同的值。某些旧版本的mysql

不允许这样做

答案 1 :(得分:0)

基于我从上面的布局中想象你的架构,这个解决方案不会起作用。当bill.id 1第二次付款时会发生什么?或者当付款开始进入账单ID 2时?

试试这个..

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

虽然我不完全了解您的系统,但我认为不需要BAP列,因为您始终可以使用SUM(AMOUNT_PAID)来查看已支付的金额以及余额。