1

I have a table like this:

columns:

id | parent

records:

1 | 1
2 | 1
3 | 1
4 | 2
5 | 2
6 | 2
7 | 3
8 | 4
9 | 5

And for all parents, I want to get the first 2 records, so i should have:

1 | 1
2 | 1
4 | 2
5 | 2
7 | 3
8 | 4
9 | 5

How can I acheive this in MySQL? I need to use subqueries? Thanks.

Bill Karwin
  • 538,548
  • 86
  • 673
  • 828
Tony
  • 425
  • 1
  • 5
  • 12

2 Answers2

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
echo_Me
  • 37,078
  • 5
  • 58
  • 78
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;
Bill Karwin
  • 538,548
  • 86
  • 673
  • 828