[英]Updated multiple column in a table based on the count(*) value from another table
以下是我的選擇查詢
select orders.customerid,count(*) as count
from Orderitem
join orders on OrderItem.orderno = orders.orderno
group by customerid
我想根據customerid的count(*)值更新表“ custtable”中的“級別”和“折扣”列
如果count(*)<2,則級別= 1,折扣= 10
如果count(*)> 3,則級別= 3,折扣= 20
如果為0,則均為0
如何在Mysql中做到這一點?
因為您沒有提供測試用例,所以我自己做了。 可能不是完美的,但總比沒有好 。
SQL> create table custtable (customerid number, c_level number, discount number);
Table created.
SQL> insert into custtable
2 select 1, null, null from dual union all
3 select 2, null, null from dual;
2 rows created.
SQL>
SQL> create table orders (customerid number, orderno number);
Table created.
SQL> insert into orders
2 select 1, 100 from dual union all
3 select 3, 300 from dual;
2 rows created.
SQL>
SQL> create table orderitem (orderno number);
Table created.
SQL> insert into orderitem
2 select 100 from dual union all
3 select 300 from dual;
2 rows created.
這是您的查詢:
SQL> select d.customerid, count(*) as count
2 from orderitem i join orders d on d.orderno = i.orderno
3 group by d.customerid;
CUSTOMERID COUNT
---------- ----------
1 1
3 1
SQL>
為了執行更新 ,我建議使用MERGE
語句,例如
SQL> merge into custtable t
2 using (select d.customerid, count(*) as cnt
3 from orderitem i join orders d on d.orderno = i.orderno
4 group by d.customerid
5 ) x
6 on (t.customerid = x.customerid)
7 when matched then update set
8 t.c_level = case when x.cnt < 2 then 1
9 when x.cnt > 3 then 3
10 when x.cnt = 0 then 0
11 end,
12 t.discount = case when x.cnt < 2 then 10
13 when x.cnt > 3 then 20
14 when x.cnt = 0 then 0
15 end;
1 row merged.
結果:
SQL> select * From custtable;
CUSTOMERID C_LEVEL DISCOUNT
---------- ---------- ----------
1 1 10
2
SQL>
您可以在UPDATE
語句中使用相關子查詢來執行此操作:
update custtable
set (level, discount) =
(select (case when count(*) = 0 then 0
when count(*) <= 2 then 1
else 3
end) as level,
(case when count(*) = 0 then 0
when count(*) <= 2 then 10
else 20
end) as discount
from Orderitem oi join
orders o
on oi.orderno = o.orderno
where o.customerid = custtable.customerId
);
注意,Oracle可以讓你在在同時更新多個列update
。
我還略微更改了邏輯,因此包括了“ 2”的計數。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.