How to fetch data from a third table based on the associative table

4

To contextualize: I have a table called principal and another called school. There are schools that are directors that are registered under the name of the school. In the case, these schools are registered in the school table and the association between director and school is made by an associative table school_director. Where I get the id of the two and form membership on the table.

Doubt: How do I update the e-mails of the respective schools (directors with school names) that are in the directors table? The id's are not the same and the name is also not spelled the same in both tables. I only have the associative table as a support for this.

Structure of tables:

CREATE TABLE IF NOT EXISTS 'diretor' (
  'id' int(11) unsigned NOT NULL AUTO_INCREMENT,
  'email' varchar(250) NOT NULL,
  'nome' varchar(250) NOT NULL,
  PRIMARY KEY ('id'),
  UNIQUE KEY 'email' ('email'),
) ENGINE=InnoDB CHARSET=utf8;

CREATE TABLE IF NOT EXISTS 'diretor_escola' (
  'id' int(10) unsigned NOT NULL AUTO_INCREMENT,
  'idDiretor' int(10) unsigned NOT NULL,
  'idEscola' int(10) unsigned NOT NULL,
  PRIMARY KEY ('id'),
  KEY 'idDiretor_idEscola' ('idDiretor','idEscola'),
  CONSTRAINT 'idDiretor' FOREIGN KEY ('idDiretor') REFERENCES 'diretor' ('id') ON DELETE CASCADE ON UPDATE CASCADE,
  CONSTRAINT 'FK_idEscola' FOREIGN KEY ('idEscola') REFERENCES 'escola' ('id') ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB CHARSET=utf8;


CREATE TABLE IF NOT EXISTS 'escola' (
  'id' int(10) unsigned NOT NULL AUTO_INCREMENT,
  'nome' varchar(250) NOT NULL,
  'codigo' varchar(250) NOT NULL,
  'email' varchar(250) NOT NULL,  
  PRIMARY KEY ('id')
) ENGINE=InnoDB CHARSET=utf8;
    
asked by anonymous 01.09.2017 / 18:43

1 answer

2

Basically you will use the table keys to link them. I set up an example without knowing the name of the columns, but it is something like:

UPDATE e
   SET e.email = d.email
  FROM escola e
       INNER JOIN escola_diretor ed ON ed.idEscola = e.id
       INNER JOIN diretor d ON d.id= ed.idDiretor
    
01.09.2017 / 18:48