I have a script like this:
There are two tables, table1 and table2 . table1 has a primary key pkey and table2 now has a foreign key fkey during insertion, if a foreign key is provided, the value should be inserted as is. Otherwise, it must obtain the primary key from table1 using some calculations and determine the foreign key to be inserted. How to do it?
I am using MySql 5.0
EDIT
In my script, table1 stores billing information, that is, table1 has invoices and the total amount payable. The client pays a certain amount of the total outstanding balance or will pay for a specific account. I want to do here. When I have not been given bill_id (which is the primary key in table1 and the foreign key in table2 ), I would like to find the oldest account that should be in table1 , and subtract the amount due and further subtract the remaining amount, if any, from the next invoice in the order. I want to do this in a database layer, not at the top level. Therefore, when the insertion is performed without a value for the foreign key, the value must be retrieved and placed by a trigger or otherwise directly inserted. How do I achieve this?
Using the answers given here, I tried this:
CREATE DEFINER=`root`@`localhost` TRIGGER `inflow_pay_done_insert` BEFORE INSERT ON `inflow_pay_done` FOR EACH ROW BEGIN DECLARE pkey INT; SET pkey = (SELECT bill_id from inflow_bills where payment_stat = 0 and rs_id = NEW.rs_id order by time_stamp limit 1); SET NEW.bill_id = IF(NEW.bill_id , NEW.bill_id , pkey); UPDATE raw_mat_sup rms SET rms.outstanding_bal_payable = rms.outstanding_bal_payable - NEW.amount where rms.rs_id = NEW.rs_id; END|
and I get the following error when I try to insert into inflow_pay_done:
/ * SQL error (1048): Column "bill_id" cannot be null * /
source share