MySql查询 - 通过id desc按不同的作者顺序查找文章

时间:2018-03-30 05:13:37

标签: mysql sql

我有article table我想要获取最新的3篇文章,但作者应该是唯一的。

我的表结构是:

article table
id | author_id
1  |    1   
2  |    1   
3  |    2   
4  |    4   
5  |    4   
6  |    5   
7  |    5  

预期输出:article id => 7 ,5, 3

我试过了:

SELECT DISTINCT(user_id), id
FROM articles 
ORDER BY id DESC
LIMIT 3

2 个答案:

答案 0 :(得分:2)

试试这个:

SELECT MAX(id)
FROM articles 
GROUP BY user_id
ORDER BY MAX(id) DESC
LIMIT 3

Demo here

答案 1 :(得分:1)

试试这个

select max(id) from article group by author_id order by id desc  limit 3;

答案就像是

mysql> select max(id) from article group by author_id order by id desc  limit 3;
+---------+
| max(id) |
+---------+
|       7 |
|       5 |
|       3 |
+---------+
3 rows in set (0.01 sec)