I have two columns named 'Name' in two different tables. One is in the Store table the other is in the Product table. How do I differentiate which one is read?
我在两个不同的表中有两个名为“Name”的列。一个在Store表中,另一个在Product表中。如何区分读取哪一个?
The data is taken from 4 different tables using left joins as shown in the query below.
使用左连接从4个不同的表中获取数据,如下面的查询所示。
var conn = new SqlConnection("serverinfo");
SqlCommand query = new SqlCommand("SELECT Store.StoreID, Store.Name,
Product.Name, " +
" StockRequest.Quantity, StoreInventory.StockLevel from Store" +
" LEFT JOIN StoreInventory ON StoreInventory.StoreID = Store.StoreID"
+ " LEFT JOIN Product ON StoreInventory.ProductID =
Product.ProductID" + " LEFT JOIN StockRequest ON StockRequest.StoreID
= Store.StoreID", conn);
SqlDataReader read;
try {
conn.Open();
read = query.ExecuteReader();
while (read.Read()) {
Console.WriteLine("{0} {1} {2} {3} {4}",
read["StoreID"],
read["Name"],
read["Name"],
read["Quantity"],
read["StockLevel"]);
}
conn.Close();
} catch (Exception e) {}
The table names are Store, Product, StockRequest, StoreInventory.
表名是Store,Product,StockRequest,StoreInventory。
Right now the data for both of the 'Name' columns are taken from the Store table. I am unable to take the 'Name' data from the Product table.
现在,两个“名称”列的数据都来自Store表。我无法从Product表中获取'Name'数据。
1 个解决方案
#1
1
You could use alias to give a different name to the duplicate column.
您可以使用别名为重复列指定不同的名称。
SqlCommand query = new SqlCommand("SELECT Store.StoreID,
"Store.Name as StoreName," +
"Product.Name as ProductName," +
" StockRequest.Quantity, StoreInventory.StockLevel from Store" +
" LEFT JOIN StoreInventory ON StoreInventory.StoreID = Store.StoreID"
+ " LEFT JOIN Product ON StoreInventory.ProductID =
Product.ProductID" + " LEFT JOIN StockRequest ON StockRequest.StoreID
= Store.StoreID", conn);
Then just use the right name when reading it, like:
然后在阅读时使用正确的名称,例如:
read["StoreID"],
read["StoreName"], read["ProductName"],
read["Quantity"], read["StockLevel"]
#1
1
You could use alias to give a different name to the duplicate column.
您可以使用别名为重复列指定不同的名称。
SqlCommand query = new SqlCommand("SELECT Store.StoreID,
"Store.Name as StoreName," +
"Product.Name as ProductName," +
" StockRequest.Quantity, StoreInventory.StockLevel from Store" +
" LEFT JOIN StoreInventory ON StoreInventory.StoreID = Store.StoreID"
+ " LEFT JOIN Product ON StoreInventory.ProductID =
Product.ProductID" + " LEFT JOIN StockRequest ON StockRequest.StoreID
= Store.StoreID", conn);
Then just use the right name when reading it, like:
然后在阅读时使用正确的名称,例如:
read["StoreID"],
read["StoreName"], read["ProductName"],
read["Quantity"], read["StockLevel"]