Question

I have two tables that I want to join and use to fill a data table, and I am having an issue with column name collision:

-----------    -----------
| Parent  |    | Child   |
-----------    -----------
| ParentID|    | ChildID |
| Name    |    | ParentID|
| Value   |    | Name    |
-----------    | Value   | 
               -----------

The SQL statement (MySQL database, in case it's relevant)

select p.*, c.* from parent p left join child c on c.ParentID = c.ChildID

My adapter code (C#):

var adapter = new MySqlDataAdapter(sql, DBConn);
adapter.Fill(table);

When I go to read the rows, i expect something like this:

var parentName = row["p.Name"];
var childName = row["c.Name"];

Instead, it is resulting in this:

var parentName = row["Name"];
var childName = row["Name1"];

How do i get the column names to use the aliases? I feel like I am missing something obvious, because this seems like it should come up all the time.

Was it helpful?

Solution

Since name is a common column name for both tables, you have to give an alias in your query to any of them. If you do not provide one, it will provided automatically one for the repeated fields, in that case appending a "1".

In addition, c. and p. are only internal alias for your query but they not form part of the returning column names.

In your SQL query put the alias (at least one of them)

SELECT p.name as parent_name, c.name as child_name, ….

And in your C# code use the proper columns

var parentName = row["parent_name"];
var childName = row["child_name"];

OTHER TIPS

Whenever you are dealing w/ sql strings its always a good convention to write out all your field names instead of using *

In this case your problem is that you have name in your query twice, so its auto populating a 1 after it to disambiguate.

Try this instead:

select
    p.ParentId,
    p.Name as parent_name,
    p.Value as parent_value
    c.ChildId,
    c.Name as child_name,
    c.Value as child_value
from parent p left join child c on p.ParentID = c.ChildID

Your c# code would need to reflect this as well.

var parentName = row["parent_name"];
var childName = row["child_name"];

The aliases in the query are for mysql to know what you mean, if you want unique column names in the output

Select p.Name as ParentName, c.Name as ChildName .... etc

I certainly wouldn't rely on the Name1 drivel, change your query to select c.*, p.* and things will go mental.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top