I have a PHP/MySQL project I am currently working on and have become stuck on a complicated (or at least to me) Insert function.
3 tables that apply here are
Client Fields that are relevant here are, clientpk (AI primary key) and clientscope.
Templatedocs , Fields that are relevant are templatepk, doctype, doctitle, templatescope
ClientDocs Fields that are relevant docpk, doctype, doctitle
What I want to do is have a code after I add a new record in client table that inserts records from the templatedocuments table into the clientdocuments table where client.clientscope = templatedocuments.templatescope, and I suspect it will be a foreach function.
I have only ever worked with insert queries that insert from one table to another, not where 3 tables are used.
If someone could give me a basic idea then I should be able to figure the rest out, thank you.
UPDATE: What I am struggling here is say ClientTable is Table A, TemplateDocuments is Table B and ClientDocuments is TableC. I know how to insert records from table A to Table C when I am writing an insert function from within Table A. However I do not know how to Insert from table B (which is an unrelated resources table essentially) data into table C, using current variables from table B.
To put it into context, Table B now has 147 different records in, only 50 of them will end up in each table C, because there are variations, it is the client.clientscope and templatedocuments.template scope that filters which are relevant records to insert.
You can use join
s in the insert.. select
syntax:
INSERT INTO clientdocuments (doctype, doctitle)
SELECT doctype, doctitle
FROM templatedocuments t
JOIN client c ON t.templatescope = c.clientscope
WHERE client.clientpk = 123
you can use trigger something link this on mysql side:
DELIMITER $$
USE `databaseName`$$
DROP TRIGGER /*!50032 IF EXISTS */ `trigger_TableName`$$
CREATE
TRIGGER `trigger_Templatedocs` AFTER UPDATE ON `Client`
FOR EACH ROW BEGIN
IF NEW.field <> OLD.field THEN
INSERT INTO Templatedocs (fieldName, fieldName2) VALUES (NEW.field, NEW.field);
END IF;
END;
$$
DELIMITER ;
im not sure it's work for you or not but you can try this.
You can get it done using AFTER INSERT
trigger on client
table; something like below
DELIMITER $$
create trigger trg_insert_clientdocs
after insert on Client
for each row
begin
INSERT INTO ClientDocs(doctype, doctitle)
select td.doctype, td.doctitle
from Templatedocs td
where td.templatescope = new.clientscope;
END$$
DELIMITER ;
Above trigger code will insert record to ClientDocs
table from Templatedocs
table based on a match on templatescope
column; where the value of templatescope
column is same as newly inserted value in Client
table clientscope
column.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.