我在尝试理解我的表格在数据库中应该如何关联时遇到问题。我是初学者,并试图自己研究。表格如下
CREATE TABLE PIZZA
(
pizza_id INT AUTO_INCREMENT PRIMARY KEY,
pizza_name VARCHAR (255),
pizza_desc VARCHAR (255),
pizza_price DOUBLE
);
CREATE TABLE CUSTOMER
(
cust_id INT AUTO_INCREMENT PRIMARY KEY,
cust_first_name VARCHAR (255),
cust_last_name VARCHAR (255),
cust_street VARCHAR (255),
cust_apt VARCHAR (255),
cust_city VARCHAR (255),
cust_state CHAR(2),
cust_zip CHAR(5),
cust_home_phone CHAR(10),
cust_mobile_phone CHAR(10),
cust_other_phone CHAR(10)
);
CREATE TABLE PIZZA_ORDER
(
pizza_order_id INT AUTO_INCREMENT PRIMARY KEY,
pizza_id INT,
cust_id INT,
order_date TIMESTAMP,
order_quantity INT,
order_notes VARCHAR (255),
FOREIGN KEY (pizza_id) REFERENCES PIZZA(pizza_id),
FOREIGN KEY (cust_id) REFERENCES CUSTOMER(cust_id)
);
我的问题是,如果PIZZA_ORDER表中的记录让我们说两个不同的披萨,意味着两个不同的pizza_ids,它将如何运作?我只是想让PIZZA_ORDER的主键不唯一,每个实际订单都有x个记录。但我不确定这是怎么回事。再次感谢你们对此有所了解。
答案 0 :(得分:1)
销售订单包含多个销售订单行项目
create table orders (
id int primary key,
...
);
create table order_items (
order_id int references orders(id),
line int,
pizza_id int references pizza(id),
...
primary key (order_id, line)
);
请参阅https://dba.stackexchange.com/questions/12991/ready-to-use-database-models-example/23831#23831以节省时间:)
答案 1 :(得分:0)
您应该在pizza_order
到pizza
表之间以及Customer
到pizza_order
表之间建立关系。这就像说,每个披萨都与一个/多个披萨订单有关;而每个披萨订单都与一个/多个客户有关。
CREATE TABLE PIZZA_ORDER
(
pizza_order_id INT AUTO_INCREMENT PRIMARY KEY,
order_date TIMESTAMP,
order_quantity INT,
order_notes VARCHAR (255),
cust_id int,
FOREIGN KEY (cust_id) REFERENCES CUSTOMER(cust_id)
);
CREATE TABLE PIZZA
(
pizza_id INT AUTO_INCREMENT PRIMARY KEY,
pizza_name VARCHAR (255),
pizza_desc VARCHAR (255),
pizza_price DOUBLE,
pizza_order_id INT,
FOREIGN KEY (pizza_order_id) REFERENCES PIZZA_Order(pizza_order_id)
);