[英]count function inside case statement
問題陳述:
如果教師教授的課程數小於1,則使用一個命令將薪水更新為30000,否則為35000。 我寫的代碼導致錯誤,你能告訴我為什么它不工作以及我如何改進它。 提前致謝
使用oracle sql更新
模式:
教師 - > id,name,dept_name,salary
教 - > id,course_id,學期,一年
update i
set i.salary = case
when count(t.course_id) < 1 then 30000
else 35000
from (select * from instructor i inner join teaches t on i.id = t.id)
這是一個例子; 我創建了自己的桌子(因為你沒有提供你的桌子),我希望它有意義。
SQL> create table instructor (id_instructor number, salary number);
Table created.
SQL> insert into instructor values (1, 100);
1 row created.
SQL> insert into instructor values (2, 100);
1 row created.
SQL>
SQL> create table teaches (id_instructor number, id_course number);
Table created.
SQL> insert into teaches values (1, 1);
1 row created.
SQL> insert into teaches values (1, 2);
1 row created.
SQL>
由於老師ID = 2教“無”,他的薪水應該是30000.另一方面,老師ID = 2教2個班,所以他會得到35000。
SQL> update instructor i set
2 i.salary = (select case when count(*) < 1 then 30000
3 else 35000
4 end
5 from teaches t
6 where t.id_instructor = i.id_instructor);
2 rows updated.
SQL> select * from instructor;
ID_INSTRUCTOR SALARY
------------- ----------
1 35000
2 30000
SQL>
我不建議在子查詢中使用count(*)
。 count(*) < 1
實際上是說沒有行存在。 當exists
合適時,您正在使用聚合 - 這是性能損失。
所以更好的方法是:
update instructor i
set salary = (select case when exists (select 1 from teaches t where t.id_instructor = i.id_instructor)
then 30000 else 35000
end);
如果您正在學習SQL,那么您應該學習最好的方法。
update i
set i.salary = (case when t.id IS NULL then 30000 else 35000 END)
from instructor i
LEFT OUTER join teaches t on i.id = t.id
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.