MySQL SELECT unique column where other column is max

前端 未结 3 1231
无人共我
无人共我 2021-01-20 17:31

I have table like this

  id     |     serial_num     |      version     | .....
  1      |         1          |          1       | .....
  2      |         2         


        
相关标签:
3条回答
  • 2021-01-20 18:04

    Selecting id for a group by query is useless. You should only select the column you are using in group by and other columns that are being applied aggregate functions.

    Hope this works for you.

    SELECT id, 
           serial_num, 
           Max(`version`) `version`
    FROM   tbl1 
    GROUP  BY serial_num 
    
    0 讨论(0)
  • 2021-01-20 18:08

    Try this:

    SELECT yourtable.*
    FROM yourtable
    WHERE (serial_num, version) in (select serial_num, max(version)
                                    from yourtable
                                    group by serial_num)
    

    Subquery will return the maximum version for serial_num, so this will return all rows where serial_num has the maximum value. See this fiddle.

    0 讨论(0)
  • 2021-01-20 18:15

    You can use a subquery to find the max values and then join back to your table:

    select t1.id,
      t1.serial_num,
      t1.version
    from yourtable t1
    inner join
    (
      select serial_num, 
        max(version) version
      from yourtable
      group by serial_num
    ) t2
      on t1.serial_num = t2.serial_num
      and t1.version = t2.version
    

    See SQL Fiddle with Demo

    Result:

    | ID | SERIAL_NUM | VERSION |
    -----------------------------
    |  1 |          1 |       1 |
    |  3 |          2 |       2 |
    |  4 |          3 |       1 |
    |  5 |          4 |       1 |
    |  8 |          5 |       3 |
    
    0 讨论(0)
提交回复
热议问题