简体   繁体   English

通过在where子句中引用子查询的值来更新表

[英]Update a table by referencing a value from a subquery in the where clause

I have the following query where I attempt to update the customers table and increase a customers credit limit when they have an order that exceeds their credit limit, and I increase their credit limit to their maximum order + $1,000 我有以下查询,当我的客户订单超过其信用额度时,我尝试更新客户表并增加客户信用额度,然后将其信用额度增加到最大订单额+ $ 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)

The problem I am running into is that I cannot use my Max_Order col which is referenced in my subquery to set the customers credit limit. 我遇到的问题是我无法使用子查询中引用的Max_Order col来设置客户信用额度。 Is there another way I can go about setting the credit limit to the maximum value of their order when they have exceeded their credit limit? 当他们超出其信用额度时,是否可以通过其他方式将信用额度设置为订单的最大值?

Here is the sql fiddle: http://sqlfiddle.com/#!4/63dc7/69 这是sql小提琴: http ://sqlfiddle.com/#!4 / 63dc7 / 69

One approach is to use merge . 一种方法是使用merge Another is to use two subqueries, one in the where and one for the set : 另一种方法是使用两个子查询,一个在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
                 );

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM