![](/img/trans.png)
[英]Display data from two tables with foreign key in Crystal Reports using C#
[英]How to display tables data having foreign key c#
我有兩個表, tableA
和tableB
。
在tableA
我有一個列id
作為主鍵,而在tableB
, id
是一個外鍵。
現在,我想通過輸入id
號在gridview中顯示所有這兩個表的數據。 當我創建外鍵時,它僅在gridview中僅顯示一個表數據。
cmd = new SqlCommand("select * from [tableA]WHERE id=1", con);
SqlDataAdapter sda = new SqlDataAdapter(cmd);
dt = new DataTable();
sda.Fill(dt);
dataGridView1.DataSource = dt;
和用於創建表的代碼:
CREATE TABLE [dbo].[tableA]
(
[Id] INT NOT NULL,
[NAME] NCHAR(10) NULL,
PRIMARY KEY CLUSTERED ([Id] ASC)
);
和tableB:
CREATE TABLE [dbo].[tableB]
(
[Id] INT NOT NULL,
[fathername] NCHAR(10) NULL,
CONSTRAINT [FK_tableB_ToTable]
FOREIGN KEY([Id]) REFERENCES [dbo].[tableA]([Id])
);
請幫我試過但不能做。
您可以像這樣聯接表
cmd = new SqlCommand("select A.ID, A.Name, B.Id, B.fathername from [tableA] as A join [tableB] as B on A.id = B.Id WHERE A.id=1", con);
為了節省空間,我為tableA(A)和tableB(B)使用別名。
您建立的這種關系有點毫無意義,因為您可以在名稱與表( tableA
)相同的表中使用父親名稱。 如果一個父親有兩個孩子,那么您的記錄將會太多...
要了解有關聯接的更多信息,請谷歌一點。 這是一個簡單的教程
您應該使用內部聯接來顯示兩個表的結果。 像這樣:
cmd = new SqlCommand("SELECT * FROM tableA INNER JOIN tableB ON tableA.id = tableB.id where tableA.id=1", con);
SqlDataAdapter sda = new SqlDataAdapter(cmd);
dt = new DataTable();
sda.Fill(dt);
dataGridView1.DataSource = dt;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.