database - MySql Trigger that inserts a record in another table if id isn't a duplicate -
i have seen similar questions mine, nothing seems fit scenario exactly.
i have 2 tables, bills , accounts.
if bill pushed bills table , there not account, want create record in accounts table.
i have:
... before insert on bills each row begin insert accounts (id, field1, field2, field3, field4) select accountid, 'value1', value2, value3, value4 bills ((select left(accountid, 5) = 'xxxxx' | (select left(accountid, 5) = 'xxxxx' | (select left(accountid, 5) = 'xxxxx' | (select left(accountid, 5) = 'xxxxx' | (select left(accountid, 5) = 'xxxxx')) && accountid not in (select id accounts); ## know line not right end$$
from have read elsewhere on options seem on duplicate key update or insert ignore, neither of can seem make work, nor can find example insert, select, , involved.
what missing?
edit: can make insert record, depending on how have tried either "duplicate id" error, or doesnt insert record.
havent coded in mysql quite while hence please excuse if there small syntax error. however, idea needs done in following code:
before insert on bills each row begin declare @li_cnt int; select count('') @li_cnt accounts accounts.id_account = inserted.id_account; if @li_cnt = 0 insert accounts (id_account) values (inserted.id_account) end end
however, type of issue should handled @ middle tier application server level , not @ database trigger level 1 should implementing strict policies , not complying business requirements. in respect, assuming app php web app, should have bill's class method save() should checking same , inserting value in accounts table using accounts table's class , inserting row in bills table. using method 1 can make modern sophisticated logic e.g. can restrict insertion of bills specific account if accounts class method call bill insertion sends decline response. although seems require simple insertion of data accounts table when bill inserted accounts code / id doesnt exist in master accounts table, still feel coding right way in simple requirements makes platform app later scale , become pretty complicated minimum issues maintenance cost.
Comments
Post a Comment