简体   繁体   English

在case语句中计数函数

[英]count function inside case statement

Problem statement: 问题陈述:

If the number of courses an instructor teaches is less than 1 then update the salary to 30000 else to 35000 - using one command. 如果教师教授的课程数小于1,则使用一个命令将薪水更新为30000,否则为35000。 The code I wrote results in an error, could you please tell why it's not working and how I can improve it. 我写的代码导致错误,你能告诉我为什么它不工作以及我如何改进它。 Thanks in advance :D 提前致谢

UPDATE using oracle sql 使用oracle sql更新

schema: 模式:

instructor -> id, name, dept_name, salary 教师 - > id,name,dept_name,salary

teaches -> id, course_id, semester, year 教 - > 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)  

Here's an example; 这是一个例子; I created my own tables (as you didn't provided yours), I hope it'll make sense. 我创建了自己的桌子(因为你没有提供你的桌子),我希望它有意义。

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>

As teacher ID = 2 teaches "nothing", his salary should be 30000. On the other hand, teacher ID = 2 teaches 2 classes so he'll get 35000. 由于老师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>

I wouldn't recommend count(*) in the subquery. 我不建议在子查询中使用count(*) count(*) < 1 is really saying that no row exists. count(*) < 1实际上是说没有行存在。 You are using an aggregation when exists is appropriate -- and that is a performance hit. exists合适时,您正在使用聚合 - 这是性能损失。

So a better approach is: 所以更好的方法是:

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);

If you are learning SQL, you should be learning the best way to do things. 如果您正在学习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.

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