How do you select only the maximum version of a list of documents that have different versions in SQL?

后端 未结 2 487
猫巷女王i
猫巷女王i 2021-01-26 06:56

I have a database table that looks like this:

| ID | TITLE | VERSION | 
| 1  | file1 |    1    |
| 2  | file2 |    1    |
| 3  | file1 |    2    |
| 4  | file2          


        
2条回答
  •  执念已碎
    2021-01-26 07:50

    Indeed, use a subquery to obtain the MAX version, grouped by TITLE, and then join the result of it with your table to obtain the ID:

    SELECT t.*
    FROM tbl t INNER JOIN 
         (SELECT title, MAX(version) version
          FROM tbl
          GROUP BY title
         ) max_t ON (t.version = max_t.version AND t.title = max_t.title);
    

    DEMO.

提交回复
热议问题