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

PostgreSQL报错:schema "m"不存在,求SQL语句问题排查

问题分析与修复方案

报错根源:语法解析错误

报错ERROR: schema "m" does not exist是因为SQL语句的语法错误导致数据库误将表别名m解析成了schema名称。具体问题出在case语句的第二个条件:

when mm.number < m.number and mm.name ilike m.name '%maya%' then 'yes'

ilike操作符要求右侧是完整的字符串值,你直接把m.name和'%maya%'连写,数据库会错误地认为m.name是schema.table的结构,把m当作schema来查找,自然找不到对应的schema。

具体修复点

  1. 修正字符串拼接语法
    将错误的字符串拼接方式改成PostgreSQL支持的写法:

    • 使用||拼接符:
      mm.name ilike m.name || '%maya%'
      
    • 或者使用concat()函数:
      mm.name ilike concat(m.name, '%maya%')
      
  2. 消除字段歧义

    • where子句中的name ilike '%maya%'没有指定表别名,medical表有m和mm两个别名,数据库无法确定使用哪个表的name字段,需要明确指定,比如:
      where m.name ilike '%maya%'
      
    • visit not ilike '%I%'中的visit来自table2 e,需要加上表别名避免歧义:
      and e.visit not ilike '%I%'
      
  3. 可选:优化自连接逻辑
    你的inner join medical mm on mm.id = m.id会把同id的所有medical记录进行自连接,可能导致结果集重复。如果你的业务逻辑是要匹配同id且编号更小的记录,可以把条件提前写到join的on子句中,减少不必要的匹配:

    inner join medical mm
        on mm.id = m.id and mm.number < m.number
    

修复后的完整SQL示例

select m.*, e.visit,
    (case when m.order ilike '%stop%' or m.order ilike '%discontinue%' then 'no'
     when mm.number < m.number and mm.name ilike m.name || '%maya%' then 'yes'   
     when m.order ilike '%continued%' then 'yes'
     when m.order is null and (m.quantity is not null or m.for_how_long is not null) then null
     else '?'
     end) as if_renewed
from medical m
left join table2 e
    on e.id = m.id
inner join medical mm
    on mm.id = m.id and mm.number < m.number
where m.name ilike '%maya%'
    and e.visit not ilike '%I%'

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.24 19:09:21