这不是一个重复的问题,因为我在那些问题中看到并没有找到我的答案。
表example
:
id type title
1 3 sth1
2 4 sthelse
3 3 sth2
4 3 sth3
5 4 sth4
6 4 sth5
我想得到每种类型的前两行。这样的:
id type title
1 3 sth1
3 3 sth2
2 4 sthelse
5 4 sth4
我使用了group_by和limit,但是看看这个例子:
SELECT * FROM `example` WHERE type IN(3, 4) LIMIT 2;
它给了我:
id type title
1 3 sth1
2 4 sthelse
,通过使用group_by(type),它只能从每个类型中得到1行。
注意:我不想在php中创建一个循环,它可能会有15或20个查询但如果它可以用1个查询完成,那就很好了
下面是一个示例。
1)按类型
对所有结果进行排序2)然后计算每个类型
的行数3) get only ROWs where recno <3
SELECT
@nr:=IF(@lastid = e.TYPE , @nr:=@nr+1 ,1) AS recno,
@lastid:=TYPE AS last_type, e.*
FROM `example`e,
(SELECT @lastid:=0, @nr:=0) tmp
WHERE TYPE IN(3, 4)
HAVING recno < 3
ORDER BY TYPE;
结果:MariaDB [tmp]> SELECT
-> @nr:=IF(@lastid = e.TYPE , @nr:=@nr+1 ,1) AS recno,
-> @lastid:=TYPE AS last_type, e.*
-> FROM `example`e,
-> (SELECT @lastid:=0, @nr:=0) tmp
-> WHERE TYPE IN(3, 4)
-> HAVING recno < 3
-> ORDER BY TYPE;
+-------+-----------+----+------+---------+
| recno | last_type | id | type | title |
+-------+-----------+----+------+---------+
| 1 | 3 | 1 | 3 | sth1 |
| 3 | 3 | 3 | 3 | sth2 |
| 1 | 4 | 2 | 4 | sthelse |
| 3 | 4 | 5 | 4 | sth4 |
+-------+-----------+----+------+---------+
4 rows in set (0.00 sec)