想象一下你创建了三个表的N-N关系。例如,图像中有CUSTOMER(id_customer, name)
表,汽车表CAR(id_car, model, num_doors, ...)
(id_customer和id_car是各自表的主键)。
现在你创建表PURCHASE以将CUSTOMER与CARS联系起来并创建FOREIGN KEYS ......问题是什么是最佳选择?
1.PURCHASE(id_customer, id_car, date_purchase) -> Primary keys are (id_customer, id_car). Foreign keys are (id_customer->CUSTOMER.id_customer and id_car->CAR.id_car).
2.PURCHASE(id, id_customer, id_car, date_purchase) -> Primary keys are (id), Foreign keys are (id_customer->CUSTOMER.id_customer and id_car->CAR.id_car).
我的问题是什么是最佳选择,1或2,考虑到数据库中的效率和优化。
答案 0 :(得分:0)
对于多对多映射,请按照这种方式进行。
CREATE TABLE XtoY (
# No surrogate id for this table
x_id MEDIUMINT UNSIGNED NOT NULL, -- For JOINing to one table
y_id MEDIUMINT UNSIGNED NOT NULL, -- For JOINing to the other table
# Include other fields specific to the 'relation'
PRIMARY KEY(x_id, y_id), -- When starting with X
INDEX (y_id, x_id) -- When starting with Y
) ENGINE=InnoDB;
注意: