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

SQLite中LIKE搭配逻辑OR运算符排除记录不生效问题

问题根源

这是布尔逻辑使用错误。你写的筛选条件(Type not like '%LPG%') or (Type not like '%Hyster%')几乎永远成立,根本达不到排除记录的效果:

  • 对包含LPG但不包含Hyster的记录:第二个NOT LIKE条件成立,OR运算只要一个条件为真整体就为真,记录会被保留
  • 对包含Hyster但不包含LPG的记录:第一个NOT LIKE条件成立,OR运算整体为真,记录同样会被保留
  • 只有同时包含LPG和Hyster的记录才会被这个条件过滤,和你要排除两类记录的预期完全不符
修正方案

你需要保留的是既不包含LPG、也不包含Hyster的记录,两种等价写法都可以实现需求:

  • 方案1:将逻辑运算符从OR替换为AND
Select CustomerName
    ,Type
    ,sum(Quantity) as Total
     ,TimeDate 
    ,date(TimeDate) as JustDate
   ,DATE(date(TimeDate),'start of month') as BeginMonth
    , DATE(date(date(TimeDate),'start of month'),'+1 month') as BeginNextMonth
    ,DATE(date(TimeDate),'start of month','+1 month','-1 day') as EndOfMonth
     ,DATE(date(TimeDate),'start of month','-1 day')  as EndOfLastMonth
from history
where (Type not like '%LPG%') AND (Type not like '%Hyster%')
group by type,CustomerName
  • 方案2:按照德摩根定律改写,语义更贴近自然语言表述
Select CustomerName
    ,Type
    ,sum(Quantity) as Total
     ,TimeDate 
    ,date(TimeDate) as JustDate
   ,DATE(date(TimeDate),'start of month') as BeginMonth
    , DATE(date(date(TimeDate),'start of month'),'+1 month') as BeginNextMonth
    ,DATE(date(TimeDate),'start of month','+1 month','-1 day') as EndOfMonth
     ,DATE(date(TimeDate),'start of month','-1 day')  as EndOfLastMonth
from history
where NOT (Type like '%LPG%' OR Type like '%Hyster%')
group by type,CustomerName
额外优化提示

你当前SELECT子句中包含TimeDate、JustDate、BeginMonth等多个时间相关字段,但GROUP BY仅指定了type和CustomerName两个字段,SQLite默认兼容这种写法,但返回的时间值是分组内随机取的一条记录的对应值,结果不具备确定性。如果不需要这些时间字段建议直接从SELECT中移除,如果需要使用请将其补充到GROUP BY子句后,或搭配对应聚合函数取值。

内容的提问来源于stack exchange,提问作者Peter Latham Lewis

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.27 16:24:34