MySQL Select rows on first occurrence of each unique value

后端 未结 5 1139
迷失自我
迷失自我 2020-12-08 04:06

Let\'s say you have the following table (the column of interest here is cid):

+-----+-------+-------+-------+---------------------+-------------         


        
相关标签:
5条回答
  • 2020-12-08 04:40

    In MySQL 8, you would use window functions for this

    SELECT cid, pid, rid, clink, time, snippet
    FROM (
      SELECT t.*, ROW_NUMBER() OVER (PARTITION BY cid ORDER BY time) rn
      FROM t
    ) t
    WHERE rn = 1
    
    0 讨论(0)
  • 2020-12-08 04:45

    mysql has a "cheat" for this:

    select *
    from mytable
    group by cid;
    

    That's all you need, because in mysql it allows you to not aggregate the non-grouped-by columns (other databases would throw a syntax error), in which case it outputs only the first occurrence of each group-by value(s). Note though that this won't guarantee the way in which the "first" occurrence is determined (it will be just how the rows are read in)

    If you want a particular first occurrence, sort first, then apply the group-by cheat:

    select *
    from (
        -- order by the "time" column descending to get the "most recent" row
        select * from mytable order by time desc
        ) x
    group by cid
    
    0 讨论(0)
  • 2020-12-08 04:47

    I know it's an old thread, the accepted solution would only retrieve me the columns that had more than one occurrence.

    This worked for me:

    SELECT cid, pid, rid, clink, MAX(time), snippet 
    FROM mytable 
    GROUP BY cid
    
    0 讨论(0)
  • 2020-12-08 04:48

    Try this one,

    SELECT *
    FROM tableName a 
    INNER JOIN (
        SELECT cid, MIN(`time`) AS MinTime
        FROM tableName
        GROUP BY cid
    ) b 
    ON a.CID = B.cid AND a.time = b.MinTime
    
    0 讨论(0)
  • 2020-12-08 04:55

    You could use a filtering join:

    select  *
    from    (
            select  cid
            ,       min(time) as min_time
            from    YourTable
            group by
                    cid
            ) filter
    join    YourTable yt
    on      filter.cid = yt.cid
            and filter.min_time = yt.time
    
    0 讨论(0)
提交回复
热议问题