这不是重复问题,因为我在这些问题中看到但没有找到我的答案。
表示例
:
id type title
1 3 sth1
2 4 sthelse
3 3 sth2
4 3 sth3
5 4 sth4
6 4 sth5
我想获得每种类型的前 2 行。像这样:
id type title
1 3 sth1
3 3 sth2
2 4 sthelse
5 4 sth4
我玩过 group_by nd 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) 仅获取 recno < 3 的 ROW
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)
关于php - 使用 in() 获取前 x 行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32829549/