這裏有一種方法......
DROP TABLE IF EXISTS my_table;
CREATE TABLE my_table
(image_id INT NOT NULL ATO_INCREMENT PRIMARY KEY
, category ENUM('corporate', 'food', 'park', 'parties', 'rides', 'schools', 'venue') NOT NULL
);
INSERT INTO my_table (category) VALUES
('corporate'),
('food'),
('park'),
('parties'),
('rides'),
('schools'),
('venue'),
('rides'),
('schools'),
('venue'),
('food'),
('park'),
('parties'),
('rides'),
('corporate'),
('food'),
('park'),
('food'),
('park'),
('parties'),
('rides'),
('food'),
('park'),
('food'),
('corporate'),
('rides'),
('corporate'),
('parties'),
('rides'),
('corporate'),
('food'),
('schools'),
('venue'),
('venue'),
('food'),
('park'),
('parties')
;
中間結論...
SELECT x.*
, COUNT(y.image_id) temp_ranks_for_y
FROM my_table x
JOIN my_table y
ON y.category = x.category
AND y.image_id >= x.image_id
GROUP
BY x.image_id;
+----------+-----------+-------------------+
| image_id | category | temp_ranks_for_y |
+----------+-----------+-------------------+
| 1 | corporate | 5 |
| 2 | food | 8 |
| 3 | park | 6 |
| 4 | parties | 5 |
| 5 | rides | 6 |
| 6 | schools | 3 |
| 7 | venue | 4 |
| 8 | rides | 5 |
| 9 | schools | 2 |
| 10 | venue | 3 |
| 11 | food | 7 |
| 12 | park | 5 |
| 13 | parties | 4 |
| 14 | rides | 4 |
| 15 | corporate | 4 |
| 16 | food | 6 |
| 17 | park | 4 |
| 18 | food | 5 |
| 19 | park | 3 |
| 20 | parties | 3 |
| 21 | rides | 3 |
| 22 | food | 4 |
| 23 | park | 2 |
| 24 | food | 3 |
| 25 | corporate | 3 |
| 26 | rides | 2 |
| 27 | corporate | 2 |
| 28 | parties | 2 |
| 29 | rides | 1 |
| 30 | corporate | 1 |
| 31 | food | 2 |
| 32 | schools | 1 |
| 33 | venue | 2 |
| 34 | venue | 1 |
| 35 | food | 1 |
| 36 | park | 1 |
| 37 | parties | 1 |
+----------+-----------+-------------------+
所以......
SELECT x.*
FROM my_table x
JOIN my_table y
ON y.category = x.category
AND y.image_id >= x.image_id
GROUP
BY x.image_id
HAVING COUNT(y.image_id) <=4
ORDER
BY category
, image_id DESC;
+----------+-----------+
| image_id | category |
+----------+-----------+
| 30 | corporate |
| 27 | corporate |
| 25 | corporate |
| 15 | corporate |
| 35 | food |
| 31 | food |
| 24 | food |
| 22 | food |
| 36 | park |
| 23 | park |
| 19 | park |
| 17 | park |
| 37 | parties |
| 28 | parties |
| 20 | parties |
| 13 | parties |
| 29 | rides |
| 26 | rides |
| 21 | rides |
| 14 | rides |
| 32 | schools |
| 9 | schools |
| 6 | schools |
| 34 | venue |
| 33 | venue |
| 10 | venue |
| 7 | venue |
+----------+-----------+
27 rows in set (0.00 sec)
請張貼您的表格結構和雄辯的名字。 –
@VishalPatel對此有幫助嗎? –