2017-07-03 70 views
-1

我搜索了很多,但找不到合適的解決方案。mysql選擇加入數據集和c#中的數據表#

比方說像生病選擇數據:

using(MySqlConnection connection = new MySqlConnection(MyConnectionString)) 
using(MySqlCommand cmd = connection.CreateCommand()) 
{ 
    connection.Open(); 
    cmd.CommandText = "SELECT a.Id, a.Foo, b.Bar FROM tableA a, tableB b where a.Id = b.Id"; 
    MySqlDataAdapter da = new MySqlDataAdapter(cmd); 
    DataSet ds = new DataSet(); 
    da.Fill(ds); 
    DataTable dt = ds.Tables[...]; //<== here is the problem 

} 

,我想將它添加到DataTable,

如何調用表在這種情況下?

是tableA嗎?

重要的是我怎麼命名它?(我可以把它命名爲foobar嗎?)

+0

正常的一個明確的問題,但總有一個devoter,不能評論這....很傷心!我不知道爲什麼應該關閉這個問題^^ – Dwza

+0

你可以在這個上下文中命名它。 –

回答

1

目前還不清楚你真正要求的是什麼,但是由於評論和澄清的時間長,將其置於答案中。

如果您試圖從MySQL返回多個查詢結果到單個「DataSet」(可以包含多個表),那麼您的查詢可能包含多個sql語句,並且每個語句都會返回到您的數據集中表結果。例如,如果你不喜歡的東西......

using(MySqlConnection connection = new MySqlConnection(MyConnectionString)) 
using(MySqlCommand cmd = connection.CreateCommand()) 
{ 
    connection.Open(); 
    cmd.CommandText = 
@"select * from TableA; 

select * from TableB; 

SELECT a.Id, a.Foo, b.Bar FROM tableA a, tableB b where a.Id = b.Id;"; 

    MySqlDataAdapter da = new MySqlDataAdapter(cmd); 
    DataSet ds = new DataSet(); 
    da.Fill(ds); 
} 

你的數據集必須在所提供的查詢直接相關的是3個表..

ds.Tables[0] = result of tableA all records. 
ds.Tables[1] = result of tableB all records. 
ds.Tables[2] = result of JOIN query tableA and tableB. 

,那麼你可以參考他們不過本地你需要......

ds.Tables[0].TableName = "anyLocalTableNameReference". 
var t1Recs = ds.Tables[0].Rows.Count; 

等...或者,而無需顯式引用數據集和表數組引用甚至創建自己的個人數據表變量名

DataTable myLocalTableA = ds.Tables[0]; 
DataTable myLocalTableB = ds.Tables[1]; 
DataTable myJoinResult = ds.Tables[2]; 

希望通過查詢和引用返回的多個數據結果以及如何分別引用表來闡明一大堆問題。

+0

爲什麼不清楚我想要什麼?我的意思是有固定的問題,我使用的陳述也很短,並顯示加入。無論如何...最後,我可以選擇它像一個數組,如果我得到這個權利?!?! – Dwza

+0

通過設置表名'ds.Tables [0] .TableName =「foobar」',我可以將它設置爲數據表類似於'DataTable dt = ds.Tables ['foobar'];'? – Dwza