I am learning SQL to make queries and I still do not understand very well how to do them with tables that are related.
My 4 tables are the following ...
First table:
create table empleado (
id int IDENTITY(1,1),
nombreempleado varchar(255),
calle varchar(255),
ciudad varchar(255),
-- Create Clustered
CONSTRAINT pk_empleado PRIMARY KEY clustered (id)
)
Second table:
create table empresa (
id int IDENTITY(1,1),
nombreempresa varchar(255),
ciudad varchar(255),
CONSTRAINT pk_empresa PRIMARY KEY clustered (id),
)
Third table:
create table jefe (
id int IDENTITY(1,1),
id_empresa int,
nombrejefe varchar(255),
calle varchar(255),
ciudad varchar(255),
CONSTRAINT pk_jefe PRIMARY KEY clustered (id),
-- Create a Foreign Key
CONSTRAINT fk_jefe_empresa FOREIGN KEY (id_empresa) REFERENCES empresa (id)
)
Fourth table:
create table trabaja (
id int IDENTITY(1,1),
id_empleado int,
id_empresa int,
sueldo money,
CONSTRAINT pk_trabaja PRIMARY KEY clustered (id),
CONSTRAINT fk_trabaja_empleado FOREIGN KEY (id_empleado) REFERENCES empleado (id),
CONSTRAINT fk_trabaja_empresa FOREIGN KEY (id_empresa) REFERENCES empresa (id)
)
So far, the simple queries have come out correctly, the problem comes when I have to do this:
Find all employees who live in the same city and in the same city street than their bosses.
The code I have so far is the following:
SELECT nombreempleado
FROM empleado
INNER JOIN trabaja ON trabaja.id_empleado = empleado.id
INNER JOIN trabaja ON trabaja.id_empresa = empresa.id
WHERE
What condition do I have to put? Am I linking the ID correctly?
Any help would be welcome, greetings to all and thanks in advance.