-3

我有一个样本数据:

products (id, name, category_id)
(1, 'Test 1', 1)
(2, 'Test 2', 1)
(3, 'Test 3', 1)
(4, 'Test 4', 2)
(5, 'Test 5', 2)
(6, 'Test 6', 2)
(7, 'Test 7', 3)

如何构思,在 1 个 category_id 中获得 2 个产品,例如:

(1, 'Test 1', 1)
(2, 'Test 2', 1)
(4, 'Test 4', 2)
(5, 'Test 5', 2)
(7, 'Test 7', 3)
4

1 回答 1

2

尝试这个,

SELECT id, name, category_id
FROM   products p
WHERE 
(
   SELECT count(*) 
   FROM   products f
   WHERE  f.category_id = p.category_id AND
          f.id <= p.id
) <= 2;

SQLFiddle 演示

于 2012-09-28T08:58:52.683 回答