我有以下查询,当我尝试更新客户表并在订单超过其信用额度时增加客户信用额度时,我将信用额度提高到最高订单额+ $ 1,000
UPDATE CUSTOMERS SET CREDIT_LIMIT = Max_Order + 1,000
WHERE (SELECT max(AMOUNT) as Max_Order, CUST_NUM
FROM ORDERS, CUSTOMERS WHERE CUST_NUM=CUST AND AMOUNT > CREDIT_LIMIT GROUP BY CUST_NUM)
我遇到的问题是我无法使用我的子查询中引用的Max_Order col来设置客户信用额度。还有另一种方法可以在信用限额超过信用额度时将信用额度设置为订单的最大值吗?
这是sql小提琴:http://sqlfiddle.com/#!4/63dc7/69
答案 0 :(得分:1)
一种方法是使用merge
。另一个是使用两个子查询,一个在where
,一个在set
:
UPDATE CUSTOMERS
SET CREDIT_LIMIT = (SELECT MAX(AMOUNT) + 1000
FROM ORDERS o
WHERE CUST_NUM = CUST AND AMOUNT > CREDIT_LIMIT
)
WHERE EXISTS (SELECT 1
FROM ORDERS o
WHERE CUST_NUM = CUST AND AMOUNT > CREDIT_LIMIT
);