我目前正在使用水费计费系统,当业主付款时,触发器将自动从我收到负值的发票总额中计算剩余余额。
这些表是:
CREATE TABLE `owners` (
`id` int(10) NOT NULL,
`lname` varchar(20) NOT NULL,
`fname` varchar(20) NOT NULL,
`mi` varchar(15) NOT NULL,
`address` varchar(20) NOT NULL,
`contact` varchar(15) NOT NULL,
`id_no` varchar(20) NOT NULL,
`c_type` varchar(20) NOT NULL,
`u_charge` varchar(10) NOT NULL,
`date` date NOT NULL
) ENGINE=MyISAM DEFAULT CHARSET=latin1;
CREATE TABLE `payments` (
`id` int(50) NOT NULL,
`mi` varchar(50) NOT NULL,
`billtotal` varchar(50) NOT NULL,
`DateCreated` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
CREATE TABLE `invoices` (
`id` int(40) NOT NULL,
`date` varchar(50) NOT NULL,
`mi` varchar(50) NOT NULL,
`billtotal` decimal(50,0) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
CREATE TABLE `customa` (
`id` int(50) NOT NULL,
`mi` varchar(50) NOT NULL,
`balance` varchar(50) NOT NULL,
`date` date NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
这就是我尝试过的:
这就是我尝试过的
DELIMITER $$
CREATE TRIGGER `Update customa( balance)` AFTER INSERT ON `payments` FOR EACH ROW BEGIN
UPDATE 'customa' SET balance = ((SELECT SUM(invoices.billtotal) FROM invoices WHERE mi=mi) - (SELECT SUM(billtotal)
FROM payments WHERE mi = NEW.mi
));
最有趣的部分是,来自不同所有者的所有行中的值都相同
我想获得所有者的总余额=即(同一所有者的所有发票的总和(mi)-(所有付款的总和)
期待什么
owners
id | lname | fname | mi
1 Robert Koisero NM139
2 Andrew S NM125
3 Henry Y NM122
invoices
id | date | mi | billtotal
1 2019/07/12 NM139 1500
2 2019/07/19 NM125 150
3 2019/07/17 NM139 100
4 2019/07/11 NM125 200
5 2019/07/18 NM122 600
customa(balance)
id | mi | balance
1 NM139 1600
2 NM125 350
3 NM122 600
When payments are made
id | mi | billtotal |
1 NM139 300
2 NM125 50
3 NM122 800
在插入付款后,customa表应更新如下:
customa(balance)
id | mi | balance
1 NM139 1300
2 NM125 300
3 NM122 -200