我想知道是否可以将主键从一个表传递到另一个表并在THAT表中将其作为多值,然后将其作为另一个表中的复合外键引用。
情况如下:我有一个Services
表,每个服务都有一个serviceCode
主键和一个serviceFee
分配给它。
服务用于约会,最多5项服务进行预约。预约生成发票,也需要服务费来计算总费用。
到目前为止我的架构是:
service
(serviceCode,description,serviceFee)appointment
([appDate,clientNo,serviceCode] PK,roomNo)invoice
(invNo,invDate,totalFee,comment,status,[appDate,clientNo,serviceCode] FK)这甚至可能吗?虽然我想我需要添加serviceFee
作为服务主键的一部分,因此我可以将其传递给发票,因为我不确定是否可以单独将serviceFee
单独传递给发票。
我正在考虑的另一个解决方案是将约会转变为复杂的关系,因为appDate是唯一的属性,其他所有内容都是其他表的引用。然后我就把所有东西都发给发票。
答案 0 :(得分:0)
是的,你可以将复合键作为PK和FK。
转到SQLLITE Foreign Key Definition并查找"复合外键约束"
但是,您需要考虑的第一件事:表格设计中存在一个大问题。你应该避免复合PK。
你应该使用一个单独的字段作为PK,它可能是IDENTIY,GUID或其他任何东西。对于您的情况,您将遇到此设计的大麻烦
答案 1 :(得分:0)
我不确定SQLLITE。在SQL Server中,您可以这样做。
CREATE TABLE [dbo].[service](
[serviceCode] [int] IDENTITY(1,1) NOT NULL,
[description] [varchar](max) NULL,
[servicefee] [float] NULL,
CONSTRAINT [PK__service__3213E83F014935CB] PRIMARY KEY CLUSTERED
(
[serviceCode] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
CREATE TABLE [dbo].[appointment](
[appDate] [datetime] NOT NULL,
[clientNo] [int] NOT NULL,
[serviceCode] [int] NOT NULL,
[roomNo] [float] NOT NULL,
CONSTRAINT [PK__appointment__3213E83F014935CB] PRIMARY KEY CLUSTERED
(
[serviceCode] ASC,
[appDate] ASC,
[clientNo] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
CREATE TABLE [dbo].[invoice](
(invNo, invDate, totalFee, comment, status, [appDate, clientNo, serviceCode]FK
[invDate] [datetime] not NULL,
[invNo] [int] not NULL,
[totalFee] [float] not null,
[comment] [varchar](max),
[status] [varchar](max),
[appDate] [datetime] NULL,
[clientNo] [int] NULL,
[serviceCode] [int] NULL
) ON [PRIMARY]
GO
/****** Object: ForeignKey [FK_appointment_service] Script Date: 04/13/2016 10:43:41 ******/
ALTER TABLE [dbo].[appointment] WITH CHECK ADD CONSTRAINT [FK_appointment_service] FOREIGN KEY([serviceCode])
REFERENCES [dbo].[service] ([serviceCode])
GO
ALTER TABLE [dbo].[appointment] CHECK CONSTRAINT [FK_appointment_service]
GO
/****** Object: ForeignKey [FK_invoice_appointment] Script Date: 04/13/2016 10:43:41 ******/
ALTER TABLE [dbo].[invoice] WITH CHECK ADD CONSTRAINT [FK_invoice_appointment] FOREIGN KEY([serviceCode], [appDate], [clientNo])
REFERENCES [dbo].[appointment] ([serviceCode], [appDate], [clientNo])
GO
ALTER TABLE [dbo].[invoice] CHECK CONSTRAINT [FK_invoice_appointment]
GO