[英]How do I link 3 tables using foreign keys?
I have made a table named "reservations" which contains a customer id and a house id. 我制作了一个名为“预订”的表,其中包含一个客户ID和一个房屋ID。 I made tables for houses and customers as well.
我也为房屋和顾客做了桌子。 I have made a datagrid, which contains the reservations data, but I also want it to contain the customers surname and the house code.
我已经创建了一个数据网格,其中包含预订数据,但我也希望它包含客户姓氏和房屋代码。
My tables are (in SQL Server Express): 我的表是(在SQL Server Express中):
CREATE TABLE [dbo].[houses]
(
[Id] INT IDENTITY (1, 1) NOT NULL,
[Code] VARCHAR(50) NULL,
[Status] VARCHAR(50) NULL,
PRIMARY KEY CLUSTERED ([Id] ASC)
);
CREATE TABLE [dbo].[customers]
(
[Id] INT IDENTITY (1, 1) NOT NULL,
[Forename] VARCHAR(50) NULL,
[Surname] VARCHAR(50) NULL,
[Email] VARCHAR(50) NULL,
PRIMARY KEY CLUSTERED ([Id] ASC)
);
CREATE TABLE [dbo].[reservations]
(
[Id] INT IDENTITY (1, 1) NOT NULL,
[HouseId] INT NULL,
[CustomerId] INT NULL,
[StartDate] DATE NULL,
[EindDate] DATE NULL,
PRIMARY KEY CLUSTERED ([Id] ASC),
CONSTRAINT [FK_HouseId]
FOREIGN KEY ([HouseId]) REFERENCES [houses]([Id]),
CONSTRAINT [FK_CustomerId]
FOREIGN KEY ([CustomerId]) REFERENCES [customers]([Id])
);
I already created all the tables, but I don't know how to link them properly. 我已经创建了所有表,但不知道如何正确链接它们。 I want to get the data and put it in a datagrid.
我想获取数据并将其放入数据网格中。
To select all data from Reservations, customers' Surname and house code, you need to run query: 要从预订,客户的姓氏和房屋代码中选择所有数据,您需要运行查询:
Select R.*, C.Surname, H.Code
From [dbo].[reservations] R
inner join [dbo].[customers] C on C.Id = R.CustomerId
inner join [dbo].[houses] H on H.Id = R.HouseId
Try this: 尝试这个:
select r.*,c.surname,h.code from reservation r,customers c,houses h where
r.customer_id=c.customer_id and r.house_id=h.house_id
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.