1

我在 MySQL 中有两个表,其中包含大量数据。我想减去两列并显示生成列的总和......

这是我所拥有的

CREATE TABLE fin_invoice(
id MEDIUMINT NOT NULL AUTO_INCREMENT,
invoice_no INT,
total INT,
PRIMARY KEY (id)
) ENGINE=MyISAM;
INSERT INTO fin_invoice (`id`, `invoice_no`, `total`) VALUES (NULL, '1000', '1000'),
(NULL, '1001', '2000'),(NULL, '1002', '3000'),(NULL, '1003', '1200'),(NULL, '1004',     '2000'),
(NULL, '1005',   '1202'),(NULL, '1006', '220');

表二是

CREATE TABLE fin_money(
id MEDIUMINT NOT NULL AUTO_INCREMENT,
fk_invoice INT,
amount INT,
PRIMARY KEY (id)
) ENGINE=MyISAM;

INSERT INTO `fin_money` (`id`, `fk_invoice`, `amount`) VALUES (NULL, '1', '100'),
(NULL, '2', '200'),(NULL, '3', '300'),(NULL, '4', '500'),(NULL, '5', '600'),
(NULL, '6',   '800'),(NULL, '7', '50');

表二(fin_money)通过外键 fk_invoice 连接到表 1(fin_invoice)。所以关系是 fin_invoice.id=fin_money.fk_invoice

我想得到这个

+----+-------------+--------+------+---------+
| id |  total      | amount | bal  | running |
+----+-------------+--------+------+---------+
|  1 |        1000 |    100 |  900 |     900 |
|  2 |        2000 |    200 | 1800 |    2700 |
|  3 |        3000 |    300 | 2700 |    5400 |
|  4 |        1200 |    500 |  700 |    6100 |
|  5 |        2000 |    600 | 1400 |    7500 |
|  6 |        1202 |    800 |  402 |    7902 |
|  7 |         220 |     50 |  170 |    8072 |
+----+-------------+--------+------+---------+

其中 bal=total-amount 和 running 是之前 id 的 bal 和 running 之和。例如 900+0=900 和 1800+900=2700 等等。

4

1 回答 1

3

这应该使用局部变量来创建运行总计:

SELECT fi.id, 
  fi.total, 
  fm.amount,
  fi.total-fm.amount bal,
  @runTotal:=@runTotal+fi.total-fm.amount runTotal
FROM fin_invoice fi 
  JOIN fin_money fm ON fi.id = fm.fk_invoice
  JOIN (SELECT @runTotal:= 0) r;

这是SQL Fiddle

结果:

ID  TOTAL   AMOUNT  BAL    RUNTOTAL
1   1000    100     900    900
2   2000    200     1800   2700
3   3000    300     2700   5400
4   1200    500     700    6100
5   2000    600     1400   7500
6   1202    800     402    7902
7   220     50      170    8072
于 2013-02-17T17:58:22.090 回答