1. 程式人生 > >mysql group by and max

mysql group by and max

  • question

    資料庫表中有一欄位表示型別,不知道這個型別會有多少種,查出每個型別插入的最新一條資料

  • resolution

mysql> select * from article;
+------+------------+------+
| name | createDate | type |
+------+------------+------+
| li1  | 1990-09-07 |    1 |
| li2  | 1980-09-07 |    1 |
| k1   | 1993-09-07 |    2 |
| k2   | 1997-09-07 |    2 |
| n2   | 1907-09-07 |    3 |
| li3  | 1990-09-07 |    1 |
+------+------------+------+
6 rows in set (0.03 sec)
mysql> select * from article where concat(createDate,type)  in(select concat(max(createDate),type) from article group by type) order by type;
+------+------------+------+
| name | createDate | type |
+------+------------+------+
| li1  | 1990-09-07 |    1 |
| li3  | 1990-09-07 |    1 |
| k2   | 1997-09-07 |    2 |
| n2   | 1907-09-07 |    3 |
+------+------------+------+
4 rows in set (0.07 sec)