2

创建一个名为 sp_del_inactive_cust 的存储过程来删除没有订单的客户。存储过程应删除 1 行。

这是我正在使用的数据库。 (来源:bcitwebdev.com数据库图

我的直接想法是我需要对照订单表检查客户表。如果客户存在于客户表中但不存在于订单表中,这一定意味着他们没有在其客户 ID 下创建任何订单 ID。然后,如果客户没有任何订单,我必须删除他们。

我不确定如何编写这个问题的脚本。我需要帮助!请保持简单,因为我是第一学期的学生。

这是我尝试过的开始:

CREATE PROCEDURE     sp_del_inactive_cust
AS
SELECT               customers.customer_id,
                 orders.customer_id
FROM         customers
INNER JOIN           orders ON customers.customer_id=orders.customer_id
WHERE        /* customer_id is found in customers table but not in orders table */

然后我将执行该程序。

感谢 Michael Fredrickson 的帮助,这个问题得到了解答。

以下是删除所需 1 行的最终语句:

CREATE PROCEDURE        sp_del_inactive_cust
AS
DELETE                  customers
FROM                    customers
LEFT OUTER JOIN         orders ON customers.customer_id = orders.customer_id
WHERE                   orders.customer_id IS NULL;
GO

EXECUTE                 sp_del_inactive_cust;
GO
4

4 回答 4

3
CREATE PROCEDURE sp_del_inactive_cust

AS

DELETE TOP (1) c
FROM
    customers c
    LEFT OUTER JOIN orders o
        ON C.customer_id = o.customer_id
WHERE
    o.customer_id IS NULL
于 2012-12-06T20:37:19.387 回答
2

您将需要创建一个反加入来获取未下订单的客户,如下所示:

DELETE c FROM
FROM customers c LEFT JOIN orders o ON c.customer_id = o.customer_id
WHERE o.customer_id IS NULL
于 2012-12-06T20:38:05.970 回答
0
DELETE customers 
WHERE customer_id NOT IN (SELECT customer_id FROM Orders)
于 2012-12-06T21:02:28.923 回答
0

I hate to just give you the answer so I will give you an example of the inverse and let you figure out the rest

here is an example

2 tables foo {foo_id, a, b, c} bar {bar_id, foo_Id, e, f, g}

If i want to delete all records from foo that appear in the bar table I would write

delete foo where foo_id in (select foo_id from bar)

look up the "in" keyword for a real explanation also there are always many ways of doing something and you might not get the proper grade in a class if you dont do things the way the teacher wants

于 2012-12-06T20:44:30.153 回答