0

我正在为我的数据库管理类做一个项目,但我不知道如何为在 SQL 中创建的表创建文件命令。我们有两个具有两个主键的实体,我无法创建表。我想知道您是否有任何意见?旅行社表有两个主键,它是这些表中的外键,由于某种原因我无法创建这些表,我无法弄清楚。到目前为止,这是我所拥有的:
这些是​​具有外键的表,它引用具有两个主键的表:

create table rental  (rental_id integer not null,  
max_daily_mileage integer not null,  
is_unlimited_mileage char(3) not null,  
rental_start_date integer not null,  
rental_end_date integer not null,  
is_reservation_a_hold char(3),  
checked_out_mileage integer not null,  
checked_in_mileage integer not null,  
checked_out_condition char(8) not null,  
checked_in_condition char(8) not null,  
company_discount integer,  
reservation_is_cancelled char(3),  
employee_id_booked integer not null,  
employee_id_checked_out_car integer not null,  
employee_id_checked_in_car integer not null,  
discount_id integer not null,  
customer_id integer not null,  
class_id integer not null,  
car_id integer not null,  
franchise_id integer not null,  
company_id integer not null, 
primary key (rental_id), 
foreign key (discount_id) references frequent_renter_discount (discount_id), 
foreign key (customer_id) references customers (customer_id), 
foreign key (travel_agency_id) references travel_agency (travel_agency_id), 
foreign key (car_id) references car (car_id), 
foreign key (franchise_id) references franchise (franchise_id), 
foreign key (company_id) references company (company_id));  

create table customers 
(customer_id integer not null, 
employer char(15) not null, 
id_verified integer, 
employee_id integer not null,  
corporate_account_id integer not null, 
credit_card_id integer not null,  
company_id integer not null, 
primary key (customer_id), 
foreign key (employee_id) references employees (employee_id), 
foreign key (corporate_account_id) references corporate_account (corporate_account_id), foreign key (credit_card_id) references credit_card (credit_card_id), 
foreign key (company_id) references company (company_id),
foreign key (rental_id) references rental (rental_id));   

具有两个主键的表:

create table travel_agency  
(travel_agency_id integer not null,  
travel_agent_id integer not null,  
location char(15) not null,  
company_id integer not null,  
primary key (travel_agency_id,travel_agent_id), 
foreign key (company_id) references company (company_id));
4

1 回答 1

0

好吧,您不能仅在复合主键的一部分上添加外键约束。travel_agency_id integer(顺便说一句,桌子出租定义中没有字段......)

如果要引用复合 PK,则必须添加对构成密钥的所有字段的引用。

这意味着,对于桌子出租

CREATE TABLE rental  (
rental_id integer not null,  
--...,
travel_agency_id integer,
travel_agent_id integer,
PRIMARY KEY (rental_id), 
--...,
FOREIGN KEY (travel_agency_id, travel_agent_id) 
   REFERENCES travel_agency(travel_agency_id, travel_agent_id)
);  

或者更改您的设计,使用代理键,并在组合应该是唯一的字段上添加唯一约束,例如。

一般来说,顺便说一句,我会尽量避免使用复合键。

于 2013-03-06T13:07:29.297 回答