group by 排序問題

果果美屢發表於2017-05-03

表結構如下所示:現在想獲取每篇文章最新的評論

CREATE TABLE `comment` (
  `cid` int(11) NOT NULL AUTO_INCREMENT COMMENT '回覆id',
  `aid` int(11) NOT NULL COMMENT '文章id',
  PRIMARY KEY (`cid`)
) ENGINE=InnoDB AUTO_INCREMENT=27 DEFAULT CHARSET=utf8

現表資料如下所示:

mysql> select * from test.comment order by aid desc;
+-----+-----+
| cid | aid |
+-----+-----+
|   7 |   7 |
|  14 |   7 |
|  17 |   7 |
|   6 |   6 |
|  13 |   6 |
|  18 |   6 |
|   5 |   5 |
|  12 |   5 |
|  19 |   5 |
|   4 |   4 |
|  11 |   4 |
|  20 |   4 |
|  25 |   4 |
|  26 |   4 |
+-----+-----+
14 rows in set (0.00 sec)

獲取每篇文章最新的評論:

mysql> SELECT *,MAX(cid) max_id FROM test.`comment` GROUP BY aid ORDER BY max_id;
+-----+-----+--------+
| cid | aid | max_id |
+-----+-----+--------+
|   7 |   7 |     17 |
|   6 |   6 |     18 |
|   5 |   5 |     19 |
|   4 |   4 |     26 |
+-----+-----+--------+
4 rows in set (0.00 sec) 

相關文章