【问题标题】:MySQL: SELECT row which meets criteriaMySQL:符合条件的 SELECT 行
【发布时间】:2020-07-06 13:38:12
【问题描述】:

我有一个带有列的表 myTable

id、foreignID、isDefault、textValue

值可能类似于

1、1、1、空 2、1、0、空 3, 1, 0, 'ABC' 4, 2, 1, '德' 5, 2, 0, 'AB' 6、3、1、空 6, 3, 0, '德'

我想为 textValue 不为 NULL 的每个 foreignID 获取一个 textValue。

如果有多个 textValues 对于 foreignID 不为 NULL 并且其中一个具有“isDefault = 1) 我想选择这个。

有什么想法吗? :)

(所以我想获取第 3、4 和 6 行)

【问题讨论】:

    标签: mysql sql join select


    【解决方案1】:

    您可以使用row_number() 获取整行:

    select t.*
    from (select t.*, row_number() over (partition by foreignId) as seqnum
          from myTable t
          where textValue is not null
         ) t
    where seqnum = 1;
    

    或者如果你只想要textValue,使用聚合:

    select foreignId, max(textValue)
    from mytable
    where textValue is not null
    group by foreignId;
    

    【讨论】:

    • 但是如何在我的聚合中获得“isDefault”? (如果 isDefault = 1 AND textValue IS NOT NULL 我想得到这个 textValue)
    • @TikTak 。 . .第一个查询返回isDefault。否则,您的问题中未提及该列。如果您有关于isDefault 的问题并且不知道该怎么做(可能只是过滤值),然后问一个新的 问题,并清楚地解释您想要完成什么。
    【解决方案2】:

    您可以尝试以下方式 - 通过在 row_number() 中添加 order by 子句

    select *
    from (select *, row_number() over (partition by foreignId order by  isDefault desc) as rn      
          from tablename
          where textValue is not null
         ) A
    where rn= 1
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-03-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-04-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多