【问题标题】:mysql / sqlite: return id where a column has more than once a specific valuemysql / sqlite:在列具有多次特定值的情况下返回id
【发布时间】:2020-09-01 03:47:52
【问题描述】:

我有一个返回 ID 1 和 2 的子查询(例如 select ID from mytable where cccccc="aaa3")。现在我想要一个进一步的查询,将这些 ID 作为输入(1和 2) 仅返回具有多个值为 0 的 myprop 列的 ID。此 ID 为 ID 2(有 3 个这样的列)。我怎样才能做到这一点?

+-----------+--------------+----------+--------+
| ID        | myprop       |   bbbb   | cccccc |
+-----------+--------------+----------+--------+
|     1     |      1       |2000/09/10|  aaa1  |
+-----------+--------------+----------+--------+
|     1     |      0       |2002/09/20|  aaa2  |
+-----------+--------------+----------+--------+
|     1     |      3       |2012/10/01|  aaa3  |
+-----------+--------------+----------+--------+
|     1     |      4       |2012/10/01|  aaa4  |
+-----------+--------------+----------+--------+
|     2     |      1       |2012/10/01|  bbb1  |
+-----------+--------------+----------+--------+
|     2     |      0       |2012/10/01|  bbb2  |
+-----------+--------------+----------+--------+
|     2     |      0       |2012/10/01|  bbb3  |
+-----------+--------------+----------+--------+
|     2     |      0       |2012/10/01|  aaa3  |
+-----------+--------------+----------+--------+

提前谢谢你。

【问题讨论】:

    标签: mysql sql sqlite


    【解决方案1】:

    要仅返回 id,您可以使用聚合:

    select id
    from t
    group by id
    having sum(myprop = 0) >= 2;
    

    如果您想要0 的详细信息并拥有某种独特的列,那么我推荐exists,如下所示:

    select t.*
    from t
    where myprop = 0 and
          exists (select 1
                  from t t2
                  where t2.id = t.id and t2.myprop = t.myprop and
                        t2.<unique col> <> t.<unique col>
                 );
    

    如果您想要所有行,包括非 0 行,则需要稍微不同的逻辑:

    select t.*
    from t
    where (select count(*)
           from t t2
           where t2.id = t.id and t2.myprop = 0 
          ) >= 2;
    

    或者:

    select t.*
    from (select t.*, sum( myprop = 0 ) over (partition by id) as cnt_0
          from t
         ) t
    where cnt_0 >= 2;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-05-29
      • 2012-01-11
      相关资源
      最近更新 更多