You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Oracle中如何正确使用not in操作符?代码报错如何解决

问题分析

你代码的报错是语法书写错误导致的,除此之外还有逻辑冗余、缺少分组的问题,具体如下:

存在的具体问题
  • 语法错误:WHERE条件中l.country_id = c.country_id = not in(...)连续使用=运算符不符合SQL规范,NOT IN本身是比较运算符,不需要在前面额外加=,这是触发「SQL command not properly ended」错误的直接原因
  • 类型不匹配:NOT IN后子查询返回的是country_name字符串类型,但你试图用country_id类型和它比对,两者类型不统一,就算修正语法也会报类型错误
  • 逻辑冗余:你已经关联了countries表,可以直接用关联后的c.country_name过滤,不需要额外写子查询再次查询countries表
  • 缺少分组:SQL中使用了max()、min()聚合函数,非聚合的country_name字段必须添加GROUP BY分组,否则执行时也会报错
最简修正代码
create or replace view VIEW_MAXMIN as
select c.country_name,
       max(salary) max_salary,
       min(salary) min_salary
from   employees e,
       departments d,
       locations l,
       countries c
where  e.department_id = d.department_id
and    d.location_id = l.location_id
and    l.country_id = c.country_id
and    c.country_name != 'Mexico'
group by c.country_name;
NOT IN 操作符的正确用法

基础语法

字段名 [NOT] IN (值1, 值2, ... / 子查询结果集)

核心注意事项

  • IN/NOT IN本身就是比较运算符,前面不能额外加=
  • 字段类型必须和IN后面集合内的所有值、或子查询返回的字段类型完全一致
  • 若子查询返回的结果包含NULL值,NOT IN会返回空结果,这种场景更推荐使用NOT EXISTS替代

NOT IN 用法示例(仅作演示,当前场景不需要这么写)

create or replace view VIEW_MAXMIN as
select c.country_name,
       max(salary) max_salary,
       min(salary) min_salary
from   employees e,
       departments d,
       locations l,
       countries c
where  e.department_id = d.department_id
and    d.location_id = l.location_id
and    l.country_id = c.country_id
-- 正确的NOT IN写法:字段直接跟NOT IN,子查询返回和字段同类型的country_id
and    c.country_id not in (
    select country_id from countries where country_name = 'Mexico'
)
group by c.country_name;

内容的提问来源于stack exchange,提问作者nanasmuda

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.29 11:09:02