Select from 3 related SQL Server tables

Asked

Viewed 280 times

2

Good, I have the following 3 tables:

SELECT *
FROM Cartao
INNER JOIN Registo 
ON Registo.ID_Cartao=Cartao.ID_Cartao
INNER JOIN Clientes 
ON Registo.ID_Cliente=Clientes.ID_Cliente
WHERE Clientes.ID_Cliente=Registo.ID_Cliente
AND Clientes.ID_Cliente=2 

With this select I can see the cards that are registered with the client with ID 2. I would like to know which select to view the customer NOT REGISTERED cards with id 2

Thank you

  • 2

    Note that the condition expressed in the clause WHERE (Clients.Id_client=Registration.Id_client) is the same condition as the junction and therefore totally redundant and unnecessary.

2 answers

0

SELECT *
FROM Cartao
INNER JOIN Registo 
ON Registo.ID_Cartao=Cartao.ID_Cartao
INNER JOIN Clientes 
ON Registo.ID_Cliente=Clientes.ID_Cliente
WHERE Clientes.ID_Cliente=Registo.ID_Cliente
AND Clientes.ID_Cliente NOT IN (2) 

0

According to the numerical set theory applied to the bank, the correct and most performative way to obtain the result would be this:

SELECT *
FROM Cartao
left JOIN Registo 
ON Registo.ID_Cartao=Cartao.ID_Cartao
left JOIN Clientes 
ON Registo.ID_Cliente=Clientes.ID_Cliente
AND Clientes.ID_Cliente=2
WHERE Clientes.ID_Cliente is null

You will only make a selection using the logic of sets as below: Conjunto numerico aplicado a banco https://eufacoprogramas.com/wp-content/uploads/2011/05/SQL-Joins-1024x819.jpg

Taking advantage, I did not understand why in Where you put the same condition that used in Join Clientes.ID_Cliente=Registo.ID_Cliente and

Registo.ID_Cliente=Clientes.ID_Cliente

Browser other questions tagged

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