Trigger (Trigger) in phpmyadmin is copying multiplying records

Asked

Viewed 20 times

0

I am a beginner and I have little experience with Mysql, but I have studied and practiced and things are going well, and I need your help because I am stuck in a situation that I can’t find a solution to, and I have searched a lot. I’m developing a system, a somewhat more sophisticated CRUD, where I import an excel table in csv to a table in Mysql (table 1:adup_c_alunos). This step is ok. Then, I need to copy some fields from this table with their referenced data (Rows) to another one (table 2:audp_lig_alunoturma). I thought I’d do that as the data gets to the first table. So I chose to use the "Triggers" function, from phpmyadmin, which is how I know to do so far, as follows the following image:

inserir a descrição da imagem aqui

A copy is being made between the tables, but in the following way, from what I understood:

  1. A first record (Row) is copied from table 1 to table 2:
  2. In sequence, a second record is copied, plus the first one that had already been copied;
  3. Then is copied the third, plus the second, plus the first again, and so on.

Thus, until this moment in the example, in the third step we would already have in table 2 "6" records: 1 of step 1, 2 of step 2 and 3 of step 3. What I need is to copy only one of each. I’ve used DISTINCT and UNIQUE and I couldn’t find a way to solve it.

This is my question that I ask anyone who can guide me. I thank you in advance.

** UPDATE **

I tried running the code below in phpmyadmin’s SQL, but I got "syntax error in SQL next to '' on line 7"

DROP TRIGGER IF EXISTS transfer;
DELIMITER $$
CREATE TRIGGER transfer AFTER INSERT ON audp_c_alunos
FOR EACH ROW
BEGIN
    INSERT INTO audp_lig_alunoturma (id_aluno, id_turma,nomealuno, turma)
    SELECT id_alunos, id_turma, nomealuno, turma
    FROM audp_c_alunos
END; $$
DELIMITER ;

1 answer

0

Note that you are not applying filters to the query. That way you are always selecting the entire table. You must filter select (from Insert select) by the line that has been inserted.

Try to put the filter referring to the primary key (or single key) of the inserted line as (assuming the field id_alunos is a unique key):

 (...)
 FROM audp_c_alunos
 WHERE id_alunos = NEW.id_alunos
 (...)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.