【问题标题】:SELECT WHERE multiple records don't existSELECT WHERE 多条记录不存在
【发布时间】:2021-10-07 19:12:05
【问题描述】:

我有以下两张表。

尝试:

id
40
41
42
43

attempt_tags:

id    attemptid    tagid
1     40           2
2     42           4
3     40           11
4     43           10
5     44           2

我希望从 attempts 表中选择一条记录,其中(例如)tagid 2 和 11 BOTH 不存在,因此本例中的查询结果将返回除 id 40 之外的所有内容。

我最初认为this question 会是一个很好的解决方案,但我现在不那么相信了,我想在我需要选择没有很多tagid 存在的结果的情况下(例如2、11、15、18、20、25 等),这个查询最终会变得很长。

我确信有一个简单的解决方案,但我目前还没有看到。

【问题讨论】:

    标签: sql


    【解决方案1】:

    一种方法使用not exists,两次:

    select a.*
    from attempts a
    where not exists (select 1
                      from attempt_tags att
                      where att.attemptid = a.id and
                            att.tagid = 2
                     ) and
          not exists (select 1
                      from attempt_tags att
                      where att.attemptid = a.id and
                            att.tagid = 11
                     ) ;
      
    

    编辑:

    您还可以将其简化为:

    select a.*
    from attempts a
    where not exists (select 1
                      from attempt_tags att
                      where att.attemptid = a.id and
                            att.tagid in (2, 11)
                     ) ;
    

    【讨论】:

    • 谢谢 - 我认为这会起作用,但肯定有一个更简单的方法 - 我认为可能有大约 20 种不同的 tagid,因此生成一个包含 NOT EXISTS 多次迭代的查询似乎不是最好的解决方案
    • @MarkOverton 。 . .我添加了一个更简单的版本。
    • 嗨,@GordonLinoff,使用select 1 有什么原因吗?会说select id 也可以吗? P.s 我是 SQL 新手。
    【解决方案2】:

    可能的解决方案如下:

    select *
      from attempts a
     where
     (select count(t.id)
        from attempts_tag t
       where t.attemptid = a.id
         and t.tagid in (2, 11)) = 0
    
    union all
    
    select *
      from attempts a
     where not exists
     (select 1
        from attempts_tag t
       where t.attemptid = a.id);
    

    【讨论】:

    • 我不确定这是否有效 - 在示例中,它返回 ID 的 42 和 43,它应该返回 42、43 和 44
    • 我已经修改了答案,希望能成功。
    猜你喜欢
    • 1970-01-01
    • 2018-01-19
    • 1970-01-01
    • 2020-07-27
    • 1970-01-01
    • 1970-01-01
    • 2012-11-05
    • 2015-03-27
    • 1970-01-01
    相关资源
    最近更新 更多