2014-10-16 52 views
0

我得到了一個奇怪的問題 我在sql數據庫中有2個表 所以我想寫一個查詢,給出結果爲2表中的數據 2表有相同的列名狀如何在c#和Sql中只執行一次相同列的兩個表到datagridview列的查詢

admission_number
student_name
student_class 我想執行該查詢給出圖像enter image description here 正在執行查詢後得到的數據將被載入到雙贏形式的datagridview在C#編碼
我正在使用下面的代碼來進行此操作,但它完全與我的問題無關,請幫助我。

private void report() 
    { 
     dataGridView4.AutoResizeColumns(); 
     dataGridView4.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.AllCells; 


     ConnectionStringSettings consettings = ConfigurationManager.ConnectionStrings["smssms"]; 
     string connectionString = consettings.ConnectionString; 
     SqlConnection cn = new SqlConnection(connectionString); 

     SqlCommand sqlcmd = new SqlCommand(); 
     SqlDataAdapter sda = new SqlDataAdapter(); 
     DataTable dt = new DataTable(); 

     cn.Open(); 
     //pass query 

     sqlcmd = new 
SqlCommand(@"selectt.admission_number,t.student_name,t.student_class,e.admission_number,e.student_name,e.student_class 
from tenthclass_marks as t,eighth_to_ninth_marks as e ", cn); 
     sda = new SqlDataAdapter(sqlcmd); 
     //Fill the data in the SQL Data Adapter 
     sda.Fill(dt); 
     //Bind it in the DataGrid View 
     dataGridView4.DataSource = dt; 
     cn.Close(); 

    } 

回答

3

您的查詢,因爲它代表:

select t.admission_number, 
     t.student_name, 
     t.student_class, 
     e.admission_number, 
     e.student_name, 
     e.student_class 
from tenthclass_marks as t, 
     eighth_to_ninth_marks as e 

正在生產的兩個表的Cartesian Product。也就是說在tenthclass_marks每一行與每一行eighth_to_ninth_marks結合,所以如果每個表有5行,你將最終獲得25行(5×5)。

您需要使用UNION ALL的結果結合起來:

SELECT t.admission_number, 
     t.student_name, 
     t.student_class 
FROM tenthclass_marks AS t 
UNION ALL 
SELECT e.admission_number, 
     e.student_name, 
     e.student_class 
FROM eighth_to_ninth_marks AS e; 

對於什麼是值得你的C#可以清理有點太:

private void report() 
{ 
    dataGridView4.AutoResizeColumns(); 
    dataGridView4.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.AllCells; 
    string connectionString = ConfigurationManager.ConnectionStrings["smssms"].ConnectionString; 
    string sql = @"SELECT t.admission_number, 
          t.student_name, 
          t.student_class 
        FROM tenthclass_marks AS t 
        UNION ALL 
        SELECT e.admission_number, 
          e.student_name, 
          e.student_class 
        FROM eighth_to_ninth_marks AS e;"; 

    DataTable dt = new DataTable();  
    using (var adapter = new SqlDataAdapter(sql, connectionString)) 
    { 
     adapter.Fill(dt); 
    } 
    dataGridView4.DataSource = dt; 
} 
+0

謝謝了很多兄弟 – 2014-10-16 10:00:32

0

使用UNION ALL你之間兩個表

Select * from tenthclass_marks 
Union All 
Select * from eighth_to_ninth_marks 
相關問題