【问题标题】:SQLite sub query, with variable number of inputsSQLite 子查询,具有可变数量的输入
【发布时间】:2019-11-28 01:03:23
【问题描述】:

尝试为 SQLite 数据库构建一个 SQL 查询,该查询将获取给定的主题名称,并将返回所有匹配的行,而不管主题记录中的单词顺序如何。以下查询对 2 个输入按预期工作。

select name
from 
    (select name from students where tags like "%biology%") 
where 
    tags like "%physics%"

如果按以下方式传入 3 个主题输入Geo Math Zoo,则必须通过代码扩展上述查询(在这种情况下使用 Python)。有没有更好的替代方法来处理 9 到 10 范围内的输入案例?

Student表:

Name    Sub
-------------------------------------------
S1      Biology Math Geo Physics
S2      Math Geo Physics
S3      Biology Geo Math Physics Zoo       -- should be in output
S4      Biology Physics Math Geo 
S5      Biology Zoo Math Geo               -- should be in output

【问题讨论】:

  • 不要在一个字符串中存储多个值!您需要一个单独的表格,每个标签和每个名称都有一行。

标签: sql sqlite select


【解决方案1】:

您可以使用OR 运算符来搜索多个条件:

select *
from students
where tags like "%biology%"
   or tags like "%physics%"

【讨论】:

  • 感谢指针和 SQL 基础课程(很遗憾错过了这个简单的结构)。我只是添加了 AND 而不是 OR,它似乎给出了预期的输出。这种查询格式也很容易通过代码创建。
猜你喜欢
  • 2017-11-15
  • 1970-01-01
  • 2011-08-29
  • 2020-03-23
  • 2016-06-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多