我有一张这样的桌子:
列:
id | parent
记录:
1 | 1
2 | 1
3 | 1
4 | 2
5 | 2
6 | 2
7 | 3
8 | 4
9 | 5
对于所有父母,我想获得前 2 条记录,所以我应该有:
1 | 1
2 | 1
4 | 2
5 | 2
7 | 3
8 | 4
9 | 5
我怎样才能在 MySQL 中实现这一点?我需要使用子查询吗?谢谢。
我有一张这样的桌子:
列:
id | parent
记录:
1 | 1
2 | 1
3 | 1
4 | 2
5 | 2
6 | 2
7 | 3
8 | 4
9 | 5
对于所有父母,我想获得前 2 条记录,所以我应该有:
1 | 1
2 | 1
4 | 2
5 | 2
7 | 3
8 | 4
9 | 5
我怎样才能在 MySQL 中实现这一点?我需要使用子查询吗?谢谢。
try this
SELECT a.id, a.parent FROM Table1 AS a WHERE
(SELECT COUNT(*) FROM Table1 AS b
WHERE b.parent = a.parent AND b.id <= a.id) <= 2
ORDER BY a.parent ASC, a.id asc
ID PARENT
1 1
2 1
4 2
5 2
7 3
8 4
9 5
Here's a couple of different solutions to try.
SELECT id, parent
FROM (
SELECT id, (@rownum:=IF(parent=@parent, @rownum+1, 1)) AS rownum,
(@parent:=parent) AS parent
FROM (SELECT @parent := null) AS _init
STRAIGHT_JOIN MyTable
ORDER BY parent) AS t
WHERE t.rownum <= 2;
Alternative:
SELECT t1.id, t1.parent
FROM MyTable AS t1
LEFT OUTER JOIN MyTable AS t2
ON t1.parent = t2.parent AND t1.id >= t2.id
GROUP BY t1.id
HAVING COUNT(*) <= 2;