MySQL SELECT unique column where other column is max

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

I have table like this

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


        
3条回答
  •  暖寄归人
    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 |
    

提交回复
热议问题