سؤال

I was looking my source code and I found this Select statement:

SELECT ID_CLIENTE, APELIDO 
FROM DBCLIENTE 
WHERE 
   STATUS = 'A' 
   AND ID_CLIENTE = @ID_CLIENTE 

UNION 

SELECT CLI.ID_CLIENTE, CLI.APELIDO 
FROM 
   DBCLIENTE CLI 
      INNER JOIN dbCLIENTE_TRANSPORTADOR TRANS ON TRANS.ID_TRANSPORTADOR = CLI.ID_CLIENTE
WHERE 
   CLI.STATUS = 'A' 
   AND TRANS.ID_CLIENTE = @ID_CLIENTE

My question is, if I cut off the UNION and the second SELECT will I recieve the same results?

هل كانت مفيدة؟

المحلول

No you wouldn't, because in the first part you are retrieving all clientes where the cliente's id is the queried id (ID_CLIENTE = @ID_CLIENTE), whereas in the second part you get those rows where the transportador's id equals the queried id (TRANS.ID_CLIENTE = @ID_CLIENTE). Note the TRANS in the second WHERE-clause.

For example consider this data:

Cliente
ID_CLIENTE        STATUS
-----------       --------
1                 A
2                 X
3                 A


Transportador
ID_TRANSPORTADOR    ID_CLIENTE
-----------------   -----------
1                   3
2                   2
3                   1

When @ID_CLIENTE = 3 the first select would give you 3 for ID_CLIENTE, while the second would give 1. Try to understand why!

نصائح أخرى

No you should receive different results. To be more precise you will receive less data. This is because you are not essentially querying the same thing in both top and bottom SQL queries.

As you are putting an inner join in the second part over the TRANS.ID_CLIENTEwhich may be different from CLI.ID_CLIENTE which logically it should be as the latter is in fact equal to TRANS.ID_TRANSPORTADOR and there should not be two columns referring to same ID in same table in different columns unless Transportador is a type of cliente

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top