[英]Three Primary Keys relating three different tables
I have the following tables category, Restaurant, and menu. 我有以下表格类别,餐厅和菜单。
A restaurant can have more than one menu, and a restaurant can also have more than one category. 一家餐厅可以有多个菜单,而一家餐厅也可以具有多个类别。 Each menu obviously has some number of catagories, and each catagory can be a part of a number of menus.
每个菜单显然都有一些类别,每个类别可以是许多菜单的一部分。
Can I create a table that looks like this, and has 3 primary keys? 我可以创建一个具有3个主键的表格吗?
Category ID | 分类ID | Restaurant ID |
餐厅编号| Menu ID
菜单ID
1 (Appetizer) | 1(开胃菜)| 1 Chile's |
1智利的| 2 Dinner Menu
2份晚餐菜单
2 (Entree) | 2(进入)| 1 Chile's |
1智利的| 2 Dinner Menu
2份晚餐菜单
3 (Dessert) | 3(甜点)| 1Chile's |
1智利| 2 Dinner Menu
2份晚餐菜单
1 | 1 | 67 McDonalds |
67麦当劳| 3 Lunch Menu 1
3午餐菜单1
Yes, you can make a primary key of the tuple (category_id, restaurant_id, menu_type_id)
. 是的,您可以作为元组的主键
(category_id, restaurant_id, menu_type_id)
。 Better even, make a normal, integral primary key, and add another index on that tuple with uniqueness constraint. 更好的是,制作一个普通的,不可分割的主键,并在具有唯一性约束的该元组上添加另一个索引 。 It's always good to have a fast, simple primary key, but you can certainly enforce uniqueness of the triple:
拥有一个快速,简单的主键总是很好,但是您可以肯定三元组的唯一性:
CREATE UNIQUE INDEX menu_index
ON menus (category_id, restaurant_id, menu_type_id)
Or you can define the index right in the table creation: 或者,您可以在表创建中定义索引:
CREATE TABLE menus (menu_id INT AUTO_INCREMENT PRIMARY KEY,
category_id INT,
restaurant_id INT,
menu_type_id INT,
FOREIGN KEY (category_id) REFERENCES categories(category_id),
FOREIGN KEY (restaurant_id) REFERENCES restaurants(restaurant_id),
FOREIGN KEY (menu_type_id) REFERENCES menu_types(menu_type_id),
UNIQUE INDEX (category_id, restaurant_id, menu_type_id)
) ENGINE=InnoDB;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.