How to identify left and right table in the execution of multiple Joins in SQL?

Asked

Viewed 83 times

0

I’m trying to understand how to read the execution of multiple INNER Joins. If I do multiple INNER Joins my left table remains the same as the first INNER JOIN or the left table becomes the resulting table of that INNER JOIN?

I made an example at SQL Fiddle to try to understand who turns the left table. In the first INNER JOIN parents is the left table and city is the right table. But in the second INNER JOIN who turns the table left? I see three possibilities there:

-parent remains the left table; or
-city becomes the left table; or
-the table that is the result of the Internet of parents and city turns the table left.

 create table pais (
 codigo_pais int primary key,
 nome_pais varchar(50)
);

create table cidade (
  codigo_cidade int primary key,
  nome_cidade varchar(50),
  codigo_pais int
);

create table estado (
  codigo_estado int primary key,
  nome_estado varchar(50),
  codigo_pais int,
  nome_cidade varchar(50),
);



insert into pais values(1,'Brasil');
insert into pais values(2,'Portugal');
insert into pais values(3,'Espanha');

insert into cidade values(1,'Belem',1);
insert into cidade values(2,'Joao Pessoa',1);
insert into cidade values(3,'Aracaju',1);

insert into cidade values(4,'Lisboa',2);
insert into cidade values(5,'Porto',2);
insert into cidade values(6,'Braga',2);

insert into cidade values(7,'esp1',3);
insert into cidade values(8,'esp2',3);
insert into cidade values(9,'esp3',3);

insert into estado values(1, 'Port1', 2, 'Lisboa');
insert into estado values(2, 'Port2', 2, 'Braga');

insert into estado values(3, 'Esp1', 3, 'esp1');
insert into estado values(4, 'Esp2', 3, 'esp2');

insert into estado values(5, 'SE', 1, 'Aracaju');
insert into estado values(6, 'AM', 1, 'Belem');
insert into estado values(7, 'PB', 1, 'Joao Pessoa');insira o código aqui

select nome_pais, c.nome_cidade, e.nome_estado
from pais as p
inner join cidade as c
on p.codigo_pais = c.codigo_pais
inner join estado as e
on e.nome_cidade = c.nome_cidade;
  • 1

    For the case of INNER JOIN it makes no difference in the final result. But you can always impose a certain order with the use of parentheses.

  • Thank you, I had tested doing each of the tables being the left table and had not gotten different results. So that’s why!

No answers

Browser other questions tagged

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