【问题标题】:How to fetch one row inside a group in mysql according to a criteria in MySQL如何根据 MySQL 中的条件在 mysql 中的组中获取一行
【发布时间】:2021-08-10 23:20:34
【问题描述】:

我有一个这样的表格,有 8 行

+----+------+------+--------+
| id | type | attr1 | attr2 |
+----+------+-------+-------+
|  1 |    a |  abcd |  qwer |
|  2 |    a |  efgh |  tyui |
|  2 |    b |  ijkl |  opas |
|  3 |    a |  mnop |  dfgh |
|  4 |    a |  qrst |  jklz |
|  5 |    a |  uvwx |  xcvb |
|  5 |    b |  yzab |  nmqw |
|  6 |    b |  cdef |  erty |
+----+------+-------+-------+

已知类型可以是'a''b'

我需要以这样一种方式选择行,如果有不止一行具有相同的id,则选择类型为'a' 的行。否则选择存在任何类型的行。

所以我想要的结果应该是这样的

+----+------+------+--------+
| id | type | attr1 | attr2 |
+----+------+-------+-------+
|  1 |    a |  abcd |  qwer |
|  2 |    a |  efgh |  tyui |
|  3 |    a |  mnop |  dfgh |
|  4 |    a |  qrst |  jklz |
|  5 |    a |  uvwx |  xcvb |
|  6 |    b |  cdef |  erty |
+----+------+-------+-------+

我有一个 MySQL 查询

SELECT t.id,      
    CASE
        WHEN count(t.id) > 1 THEN 'a'
        ELSE t.type
    END `type`
FROM table1 t
GROUP BY  t.id
ORDER BY  t.type ASC

给出这个结果

+----+------+
| id | type |
+----+------+
|  1 |    a |
|  2 |    a |
|  3 |    a |
|  4 |    a |
|  5 |    a |
|  6 |    b |
+----+------+

但我需要包含所有列的相应行。 该怎么做?

请注意,我拥有的 MySQL 版本是 5.7.12

【问题讨论】:

    标签: mysql sql count


    【解决方案1】:

    嗯。 . .我会倾向于使用not exists:

    select t.*
    from t
    where t.type = 'a' or
          not exists (select 1
                      from t t2
                      where t2.id = t.id and t2.type = 'a'
                     );
    

    【讨论】:

      【解决方案2】:

      您也可以使用window function

      select * from 
       ( 
        select * , row_number() over (partition by id order by case when type = 'a' then 0 else 1 end) rn
       ) t
      where rn = 1;
      

      【讨论】:

        【解决方案3】:

        你没有提到是否有多个具有相同 id 的 a 是可能的,或者在这种情况下该怎么做。我将假设您希望包含所有行。为此,您只需要在有相应的 a 行时排除 b 行:

        select t.*
        from table1 t
        left join table1 t2 on t2.id=t.id and t.type='b' and t2.type='a'
        where t2.id is null;
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2015-07-30
          相关资源
          最近更新 更多