【问题标题】:SQL string search among multiple joined records在多个连接记录中进行 SQL 字符串搜索
【发布时间】:2018-07-19 21:09:07
【问题描述】:

这是在 SQLite 中。

我有两个表,X 和 Y。X 有一个“id”字段。 Y 有一个“tag”字段和一个映射到 X.id 的外键“xid”。

假设我们要处理一个字符串列表,例如 ["abacus", "baritone", "custard"]。我想选择 X 中的每条记录 N,其中 Y 包含所有这些记录:{"abacus", N.id}, {"baritone", N .id},{“奶油冻”,N.id}。

如果可能的话,处理子字符串也很好,这样我们就可以从列表 ["aba", "tone", "star"] 中得到相同的结果,但这可能要求太多了。

我可能没有很好地解释,所以我愿意在需要时澄清问题。

【问题讨论】:

    标签: sql sqlite select


    【解决方案1】:

    您可以使用group byhaving。对于第一个问题:

    select y.id
    from y
    where y.tag in ('abacus', 'baritone', 'custard')
    group by y.id
    having count(*) = 3;
    

    第二个有点复杂,因为您可以使用“malabar”或“semitone”或“astaroth”之类的标签。所以:

    select y.id
    from y
    group by y.id
    having sum(case when y.tag like '%aba%' then 1 else 0 end) > 0 and
           sum(case when y.tag like '%tone%' then 1 else 0 end) > 0 and
           sum(case when y.tag like '%star%' then 1 else 0 end) > 0;
    

    【讨论】:

    • 太棒了,我检查了您的第一个解决方案,它运行良好。对不起,我在第二点误导了你......我说“相同的结果”是错误的。如果存在“malabar”、“semitone”或“astaroth”,那么这些都是可以接受的查询结果。解决方案是否只是删除 where 子句?
    • 还有,你很快!
    • @matt_rule 。 . . where 子句不见了。
    猜你喜欢
    • 2017-12-31
    • 2018-12-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多