1
I’m new to the SQL
and I have the following question concerning LEFT JOIN
: I have to list a table of cliente
where each customer has a id and a code client with another table containing the addresses; in some cases the client has id, in others, he possesses the code.
I tried using the query below, but I do not know if it is the best choice or if it is correct.
SELECT cli.clicod, cli.atlcod, clinompessoa, grade.camnum
FROM cli
LEFT JOIN codEnd on cli.clicod = codEnd.clicod
LEFT JOIN grade on cli.clicod = grade.clicod or cli.atlcod = grade.atlcod
WHERE logcod = 32388
AND camnum = 520
summarized tables basically I want to get customers belonging to the streets that have the campaign 520, spreadsheets are old without the possibility of normalizing the data
Matthew, to be able to help you would need to post the structure of the tables that are being used in your SQL statement
– Clayton Tosatti
@Mateussilva LEFT JOIN is used when the junction is not required.
– José Diz
As far as I can see, the code is correct. The
LEFT JOIN
should be used when there is no match in the second table. If there is always a match, we can use theINNER JOIN
.– João Martins
Will
LEFT JOIN
is the ideal? understanding that it will align the left columns always and if there are then the right ones, if you want to mandatory in the result, it would no longer be appropriate aINNER JOIN
? Anyway, does your query return what you want? If yes then the question would refer to the optimization of this query and not if it is correct, I suggest doing some tests in ideal and unusual situations to check if everything goes well.– bruno101
Apparently, you are correct. What it has to do is: will the relationship of "cli" with "codEnd" not always occur, if this always occurs the recommended is to use the "INNER JOIN". About LEFT JOIN with "or" you can take a test and measure performance, develop 2 queries with the conditions you put in the relationship of the table "grid" using INNER JOIN. In this case, you would use UNION to relate your 2 queries. The other possible simpler solution, using "IN" do not recommend, is usually slower than using "LEFT JOIN".
– Augusto Filipe
I understood that the OP is wanting to OR use the code when there is OR use the id as the Join key if the code does not exist. That’s what you expect @Matthew?
– nullptr
Tell me what I want
– Mateus Silva
basically are 3 old tables
– Mateus Silva