首先,我创建了一个表“ customers”。然后,我用另一个属性“ cust_level”更新了“客户”。我还有另一个表“订单”。现在,我想基于“订单”表中订购的“数量”来更新“客户”表上的cust_level。但是,当我尝试更新表“ Customers”时,出现以下错误:
受影响的0行已匹配的行:10已更改:0警告:0
感谢您的帮助!
create table customers(
customer_id varchar(20),
PRIMARY KEY (customer_id)
);
ALTER TABLE customers ADD cust_level CHAR(1);
create table orders(
order_id int,
order_no varchar(10),
quantity int,
order_date date,
delivery_date date,
customer_id varchar(20),
PRIMARY KEY(order_id),
FOREIGN KEY (customer_id) REFERENCES customers(customer_id)
);
update customers C
left join
(
select customer_id,sum(quantity) as total_purchase from orders group by customer_id
) A on C.customer_id=A.customer_id
set C.cust_level = case
when A.total_purchase>2 then C.cust_level='3'
when A.total_purchase>0 and A.total_purchase<3 then C.cust_level='2'
else C.cust_level='1'
end
答案 0 :(得分:1)
SET C.cust_level = CASE
WHEN A.total_purchase>2 THEN C.cust_level='3'
WHEN A.total_purchase>0 AND A.total_purchase<3 THEN >C.cust_level='2'
ELSE C.cust_level='1'
END
此CASE表达式有问题。您要指定在CASE之前应更新哪一列(SET C.cust_level = ...),但要在CASE内部引用它们(...然后C.cust_level ='3')。 CASE应该返回一个值,该值将分配给指定的列。
这应该写成:
SET C.cust_level = CASE
WHEN A.total_purchase > 2 THEN '3'
WHEN A.total_purchase > 0 AND A.total_purchase < 3 THEN '2'
ELSE '1'
END
最后:当条件一个接一个地评估时,CASE在第一个匹配项时停止。因此,虽然功能等效,但可以简化为:
SET C.cust_level = CASE
WHEN A.total_purchase > 2 THEN '3'
WHEN A.total_purchase > 0 THEN '2'
ELSE '1'
END