Reputation: 700
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.
Upvotes: 2
Views: 2317
Reputation: 15865
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"];
Upvotes: 1
Reputation: 4860
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"];
Upvotes: 4
Reputation: 20320
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.
Upvotes: 0