Plateforme Level Extreme
Abonnement
Profil corporatif
Produits & Services
Support
Légal
English
Select same column from two tables
Message
De
14/02/2017 10:41:48
 
 
Information générale
Forum:
Microsoft SQL Server
Catégorie:
Syntaxe SQL
Divers
Thread ID:
01647947
Message ID:
01647949
Vues:
41
>I see the following behavior of SQL Select, when both parent and child tables have the same field name and joined in SQL Select. And the value is set in the column that is shown first in the SQL Select order. Here is an example:
>
>
>select ChildTable.FIELD_X, ParentTable.* from ParentTable JOIN ChildTable on ParentTable.Pk = ChildTable.Pk
>
>Note that the ParentTable also has field FIELD_X but the resulting query shows the value of FIELD_X from the ChildTable.
>Is this by design that since the column FIELD_X shows before the ParentTable.* it takes precedence?

Your first field explicitely confirms you want to include ChildTable.Field_X in the first query result field. So, I am assuming this is what you get. Even if ParentTable has the same field name, as part of the * result, this should not matter.

One thing I have found to avoid confusion is to always prefix a field name by its table name, very useful when using multiple tables in queries. So, instead of WHERE NoClient=12, I would always use WHERE Invoice.NoClient=12. IAC, SQL Server will complain as soon as non-prefixed table fields are used, if they relate to more than one table used in the query. So, it is a convention I have adopted. Even when I only have one table in a query, I always use the full written syntax as, if the query evolves, I won't have any problem later on.

If this is a production query, I would also avoid using ParentTable.* and use the list of only required field names. That will help the execution plan to deliver faster and improve on performance.
Michel Fournier
Level Extreme Inc.
Designer, architect, owner of the Level Extreme Platform
Subscribe to the site at https://www.levelextreme.com/Home/DataEntry?Activator=55&NoStore=303
Subscription benefits https://www.levelextreme.com/Home/ViewPage?Activator=7&ID=52
Précédent
Suivant
Répondre
Fil
Voir

Click here to load this message in the networking platform