【问题标题】:Get result true if all the rows have met the condition in sql如果所有行都满足sql中的条件,则结果为true
【发布时间】:2020-01-27 19:40:24
【问题描述】:

基本上我正在寻找条件的解决方案,其中表具有以下行,我只想选择所有行都满足条件的那些。

ID  category    flag
1       A       1
2       A       1
3       A       0
4       B       1
5       C       0

预期结果是 B,其类别的标志为真。

【问题讨论】:

  • 感谢 Fahmi 的编辑。
  • 同时指定预期结果。
  • 谢谢你的努力。我想我需要用实际的表格值发布问题,这样我才能得到想要的结果。

标签: sql


【解决方案1】:

希望我的回答对您的问题有所帮助。在子查询中,通过过滤标志创建类别列表。

SELECT * 
FROM tablename a 
WHERE a.category NOT IN (
      SELECT b.category
      FROM tablename  b 
      WHERE b.flag=0)

【讨论】:

    【解决方案2】:

    您想要最小标志为 1 的类别(意味着有 没有 flag = 0):

    select category
    from tablename
    group by category
    having min(flag) = 1
    

    请参阅demo
    结果:

    | category |
    | -------- |
    | B        |
    

    【讨论】:

    • 谢谢,但是如果我们添加另一条带有标志 0 的 B 记录,它不会显示任何结果
    • 当然它不会显示任何结果,因为 B 是 0。这是您在问题中设置的要求。
    • 实际上我正在寻找的是如果它的所有行都满足条件,则获取类别。
    • 没错。因此,如果 B 有一行为 1(true) 和一行为 0(false) 则不会返回。
    【解决方案3】:

    通过not exists使用相关子查询

    select * from tablename a 
    where not exists (select 1 from tablename b where a.category=b.cateogry and flag=0)
    

    【讨论】:

    • 感谢 Fahmi,但没有解决目的。上帝保佑
    【解决方案4】:

    试试这个

    select distinct category,flag from test where category in
    (select t.category from (select category,flag from test 
    group by category,flag)t group by t.category having count(*)=1) 
    and flag=1;
    

    【讨论】:

      【解决方案5】:

      如果您有单独的类别表,那么not exists 通常是最快的方法:

      select c.*
      from categories c
      where not exists (select 1
                        from t
                        where t.category = c.category and 
                              t.flag = 0
                       );
      

      特别是,这可以利用(category, flag) 上的索引。如果你没有这样的表,那么forpas的方案还是蛮有效的。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-10-13
        • 2015-01-25
        相关资源
        最近更新 更多