1

我有一张这样的桌子:

列:

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 中实现这一点?我需要使用子查询吗?谢谢。

4

2 回答 2

1

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

DEMO HERE

 ID     PARENT
 1       1
 2       1
 4       2
 5       2
 7       3
 8       4
 9       5
于 2013-06-12T16:19:50.603 回答
1

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;
于 2013-06-12T16:20:20.973 回答