0

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

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

| 身份证 | 血压 |

| 1 | 20 |

| 投标 | AMOUNT_PAID | 巴普 |

| 1 | 10 | (空) |

请问我该如何处理这种情况,我已尽力完成这项工作,但无济于事,任何有关如何解决此问题的想法将不胜感激。

4

2 回答 2

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 不允许这样做

于 2013-07-11T11:23:32.117 回答
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) 找出已支付的金额以及余额。

于 2013-07-11T13:28:51.130 回答