如何根据我的作业要求使SQL中的JOIN函数工作?

时间:2019-07-02 20:49:53

标签: sql join

说明:

请修改以下两个SQL命令以解决后续任务:

调整表ORDERS和CUSTOMERS之间的关系,其中CUSTOMERS表的ID字段应为主键,而ORDERS表的ID_CUSTOMER字段应为外键字段。删除客户后,还应该删除其所有订单。

我的工作:

CREATE TABLE CUSTOMERS (id int primary key, firstname varchar(30), 
    lastname varchar(30), ADDRESS VARCHAR(100));

CREATE TABLE ORDERS (ID INT primary key, 
   PRODUCT_NAME VARCHAR(30), 
   PRODUCT_PRICE FLOAT,
   DATE_ORDER DATE,
   ID_CUSTOMER INT,
   AMOUNT INT);

ALTER TABLE ORDERS
ADD FOREIGN KEY (ID_CUSTOMER)
REFERENCES ORDERS (ID)
;

预期结果(根据作业系统):

CUSTOMERS|1
ORDERS|2
DELETE ONE RECORD IN CUSTOMERS
CUSTOMERS|0
ORDERS|0

为什么呢?我应该怎么做才能除去客户?

  

删除客户后,所有客户的订单也应删除。

2 个答案:

答案 0 :(得分:1)

尝试这个:

CREATE TABLE CUSTOMERS (id int primary key,
    firstname varchar(30),
    lastname varchar(30),
    ADDRESS VARCHAR(100));

CREATE TABLE ORDERS (ID INT primary key,
   PRODUCT_NAME VARCHAR(30),
   PRODUCT_PRICE FLOAT,
   DATE_ORDER DATE,
   ID_CUSTOMER INT,
   AMOUNT INT,
   FOREIGN KEY(ID_CUSTOMER) REFERENCES CUSTOMERS(id)
   ON DELETE CASCADE);

答案 1 :(得分:0)

带有ON DELETE CASCADE的外键将导致在删除记录引用时删除该记录。

ALTER TABLE ORDERS
ADD FOREIGN KEY (ID_CUSTOMER)
REFERENCES ORDERS (ID)
ON DELETE CASCADE