Sql 基于筛选器字段和中间字段从表中获取记录,但也具有多行的OR逻辑

Sql 基于筛选器字段和中间字段从表中获取记录,但也具有多行的OR逻辑,sql,sqlite,Sql,Sqlite,我在这个表中有一个存储多个ID和一个年龄范围(def1,def2)的 具有如下价值: templateid | def1 | def2 ------------------------------- 100 | 7 | 25 200 | 40 | 90 300 | 7 | 25 300 | 40 | 60 正如您看到的templateid300,我们有一个or逻辑:年龄在7到25岁之间,或者年龄在40到60岁之间 我想

我在这个表中有一个存储多个ID和一个年龄范围(def1,def2)的

具有如下价值:

templateid | def1 | def2
-------------------------------
100        | 7    | 25
200        | 40   | 90
300        | 7    | 25
300        | 40   | 60
正如您看到的templateid
300
,我们有一个or逻辑:年龄在7到25岁之间,或者年龄在40到60岁之间

我想获得所有的模板ID,这些ID在某个
年龄
比如25岁时是而不是。。。
有什么问题吗

如果我运行这样的查询:

SELECT group_concat(templateid) 
 FROM template_requirements 
where 1=1 and '25' not between cast(def1 as integer) 
                       and cast(def2 as integer)
它返回200300,这是错误的,因为第40行到第60行的300匹配,但不应该包含在结果中,因为我们有一个模板ID为7到25的条件,该条件不能满足not beetween的条件


在SQLite中正确的查询是什么,我想保留组内容。

您可以尝试
,除了

sqlite> select group_concat(templateid)
          from (select templateid from template_requirements
                except
                select templateid from template_requirements
                 where 25 between cast(def1 as integer) and cast(def2 as integer));
。。。给我看看那些
“templateid”
s,年龄范围在25岁的除外

或者类似的
,不在
中的情况如何:

sqlite> select group_concat(distinct templateid)
          from template_requirements
         where templateid not in
                 (select templateid from template_requirements
                   where 25 between cast(def1 as integer) and cast(def2 as integer));

这两个都是相当“口语准确”的SQL表示,表示您正在尝试执行的操作…

我认为我不是sqlite,而是查询,请尝试以下操作:

SELECT templateid
FROM template_requirements 

/*You want this values*/
WHERE '25' not between cast(def1 as integer) and cast(def2 as integer)

/*You don't want results with this values (with this you should eliminate 300)*/
AND templateid NOT IN (
  SELECT templateid
  FROM template_requirements 
  WHERE '25' between cast(def1 as integer) and cast(def2 as integer)
  )

你有一个语法错误;在
'25'
之前的
。是的,很抱歉,我还有一些其他的东西,我发布了一个简化的表格模式更新了您的第一个提议,以进行分组讨论,我会接受它。请再次查看查询,不是那么简单,该组不会在该位置工作,因为它会将所有字段合并在一起,并根据except处理连接的字符串。
SELECT templateid
FROM template_requirements 

/*You want this values*/
WHERE '25' not between cast(def1 as integer) and cast(def2 as integer)

/*You don't want results with this values (with this you should eliminate 300)*/
AND templateid NOT IN (
  SELECT templateid
  FROM template_requirements 
  WHERE '25' between cast(def1 as integer) and cast(def2 as integer)
  )