比如有个news
的table,字段有id,categoryid,content
,值如下:
id | categoryid | content |
---|---|---|
1 | 1 | text1 |
2 | 2 | text2 |
3 | 1 | text |
4 | 3 | text |
5 | 1 | text |
6 | 1 | text |
7 | 1 | text |
8 | 2 | text |
9 | 2 | text |
10 | 3 | text |
11 | 2 | text |
12 | 1 | text |
13 | 1 | text |
我想得到的值如下:
id | categoryid | content |
---|---|---|
13 | 1 | text1 |
12 | 1 | text1 |
11 | 3 | text |
10 | 2 | text |
7 | 1 | text1 |
6 | 1 | text1 |
即,取同一表中的,分类为1的最新4条,分类2和分类3的最新一条数据。
不知道这个应该怎么实现???
刚才试了下
SELECT * from news where id in (select id from news where categoryid = 1 ORDER BY id DESC LIMIT 4) ORDER BY id DESC;
上面的sql语句是错误的,好像不能在里面用limit
,不知道是否要使用INNER JOIN
这种语法来写?求思路或者语句。
非常感谢。
通过id排序,取前4条记录
SELECT * from news WHERE categoryid = 1 ORDER BY id DESC LIMIT 4