如何使用引用具有两个主键的表的外键在SQL中创建命令文件?

时间:2013-03-06 12:52:26

标签: mysql

我正在为我的数据库管理类做一个项目,我无法弄清楚如何为在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));

1 个答案:

答案 0 :(得分:0)

好吧,你只是不能在复合PRIMARY KEY的一部分上添加FOREIGN KEY CONSTRAINT。 (顺便说一句,表租赁定义中没有字段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)
);  

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

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