【问题标题】:SQL: only show entry if there is no other entry with special different value in same tableSQL:只有在同一个表中没有其他具有特殊不同值的条目时才显示条目
【发布时间】:2014-02-13 17:55:20
【问题描述】:
ID    ID_A   Status  
175   473    2    
174   473    1    
173   455    2
170   412    2
169   397    1
168   393    2
173   391    2

这是我的示例表。结果,我希望它只显示状态 = 1、按 ID_A 分组的条目。它不能包含 Status=2 的结果! 结果应如下所示:

ID_A   Status
397    1

我的问题是可能有两个相似的 ID_A 条目。不知道使用 COUNT 或 DISTINCT 是否容易实现?不知何故,我现在不知道它..提前谢谢!

【问题讨论】:

  • SELECT DISTINCT x.id_a x.status FROM a x LEFT JOIN a y ON y.id_a = x.id_a AND y.status = 2 WHERE x.status = 1 AND y.id_a IS NULL;跨度>

标签: mysql sql select count distinct


【解决方案1】:

这有时称为排除连接

您执行外部联接以尝试查找会使您的条件无效的行。如果没有这样的行,外连接会将 NULL 放入连接表的所有列中,然后匹配。

SELECT t1.ID_A, t1.Status
FROM exampletable AS t1
LEFT OUTER JOIN exampletable AS t2
    ON t1.ID_A = t2.ID_A AND t2.Status = 2 
WHERE t1.Status = 1
    AND t2.ID IS NULL;

@Strawberry 回复评论:

2001 年的美国专利"Optimizing an exclusion join operation using a bitmap index structure" 定义了一个排除连接:

排除连接操作选择第一个表中具有指定列中的值的行,而在第二个表的指定列中找不到这些值。数据库系统可以通过排除第一个表中与第二个表中的条目匹配的条目来执行这样的查询。

该专利还引用了 1993 年的一篇论文,"Parallel implementations of exclusion joins"

我假设该术语也早于那篇论文。

【讨论】:

  • 我也将其称为排除连接,但如果我曾在任何地方看到过这样的记录,我不会这样做。
【解决方案2】:

您可以使用聚合和having 子句来做到这一点:

select id_a, group_concat(status) as statuses
from table t
group by id_a
having sum(status = 2) = 0;

【讨论】:

    【解决方案3】:

    试试

    select t.id_A,t.status
    from exampletabla as t
    where t.status = 1 and t.id_A not in (select id_A from exampletabla where status = 2)
    

    【讨论】:

      【解决方案4】:
      select distinct x.id_a, x.status
        from tbl x
       where status = 1
         and not exists (select 'y'
                from tbl y
               where x.id_a = y.id_a
                 and status = 2)
      

      【讨论】:

      • 虽然此链接可能会回答问题,但最好在此处包含答案的基本部分并提供链接以供参考。如果链接页面发生更改,仅链接的答案可能会失效。
      • 我没有在这个帖子里放任何链接,你是想评论别的吗?
      【解决方案5】:

      您可以先从列中查找唯一条目,然后根据您的条件查找确切值。

      select ID_A ,Status 
      FROM testTbl 
      group by ID_A 
      having COUNT(*) = 1 and Status  = 1;
      

      希望对你有帮助。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-05-04
        • 1970-01-01
        相关资源
        最近更新 更多