2013-01-15 119 views
-2

我是新的,有一個數據庫和兩個表:關係在SQL數據庫

UsersTable contains userID(smallInt),Name,Family 
ActivitiesTable contains WorkTime,RestTime,Date,userID(smallInt) 

我想這在一個DataGrid中(當我添加新的記錄):

userID:A WorkTime: 08:00 RestTime:14:00 Date:12.10.2012 
userID:A WorkTime: 08:30 RestTime:14:00 Date:12.11.2012 
userID:B WorkTime: 08:00 RestTime:15:00 Date:12.12.2012 
. 
. 
. 

如何可以爲兩個表(使用主鍵和外鍵)建立關係? 非常感謝

+0

關係不是你認爲的那樣。它們實際上(大致)是表格的同義詞。你所指的可能是*關係*,儘管我不確定,因爲我不太明白這個問題。 「建立關係」究竟意味着什麼?你想在查詢中加入兩個表還是在它們之間定義一個外鍵關係? –

+0

好的,我想要外鍵關係。 – mhshojaee

+0

那你爲什麼接受解答查詢解釋的答案? @ faester的答案解釋瞭如何定義一個外鍵。 –

回答

0

認沽用戶ID爲UsersTable並作爲ActivitiesTable(外鍵主鍵最終你可以把它作爲主鍵以及如果連接是一對一的)。 然後用這個片段填充你的DataGridView(它顯示瞭如何顯示一個完整的數據列表)。如果你想繼續使用DataBinding,我建議不要逐個添加全新的項目,而只是刷新底層的DataTable並刷新DataGridView。

基本上,優化可能會將新行添加到DataTable並刷新,而不從數據庫獲取所有數據(因爲已經擁有它,因爲您剛剛將其插入到數據庫中)。

對不起,我的英語不好。我希望我很清楚。

try 
    { 
     var bindingSource1 = new BindingSource(); 

     // Automatically generate the DataGridView columns. 
     dataGridView1.AutoGenerateColumns = true; 

     // Set up the data source. 
     bindingSource1.DataSource = GetData("Select * From UsersTable Inner Join ActivitiesTable")); 
     dataGridView1.DataSource = bindingSource1; 

     // Automatically resize the visible rows. 
     dataGridView1.AutoSizeRowsMode = 
DataGridViewAutoSizeRowsMode.DisplayedCellsExceptHeaders; 
    } 
    catch (SqlException) 
    { 
     // TODO manage errors 
    } 
} 

private static DataTable GetData(string sqlCommand) 
{ 
    var connectionString = "%your connection string%"; 
    var northwindConnection = new SqlConnection(connectionString); 
    var command = new SqlCommand(sqlCommand, northwindConnection); 
    var adapter = new SqlDataAdapter(); 

    adapter.SelectCommand = command; 

    var table = new DataTable(); 
    table.Locale = System.Globalization.CultureInfo.InvariantCulture; 
    adapter.Fill(table); 

    return table; 
} 

P.S.如果您使用DB服務器/引擎提供程序Linq擴展,則可以使用它代替硬編碼查詢(SqlCommand +字符串)(僅從下面的答案中獲取代碼)。

1
SELECT name, workTime, restTime, [date] 
FROM usersTable u 
JOIN activitiesTable a 
ON  a.userId = u.userId 
+0

它的內部連接...我認爲不僅加入.. –

+0

@PranayRana:JOIN意味着內部連接。內部連接比外部連接更加普遍,因此大多數人不會浪費擊鍵來明確表示。 –

+0

@MarceloCantos - 感謝您的信息.. –

1

你可以創建一個使用

CREATE TABLE UsersTable (userID smallInt NOT NULL PRIMARY KEY, 
     Name NVARCHAR(255), 
     Family NVARCHAR(255)) 

CREATE TABLE ActivitiesTable (WorkTime DATETIME, 
    RestTime DATETIME,Date DATETIME, 
    userID smallInt NOT NULL REFERENCES UsersTable (userid), 
    id int not null identity (1,1)) 

我增加了一個ID列ActivitiesTable。你也應該考慮使用INT而不是smallint,因爲在大多數情況下性能和空間增益是可以忽略的。

而作爲其他答覆正確地指出的選擇很簡單

Select v.userID, WorkTime, RestTime, Date 
from userTable user inner join ActivitiesTable activity 
on user.userid = activity.userid