I've been stuck in a complex MySQL query. Here is my table:
+--------------------------------------+
| id | user_id | category_id | post_id |
+--------------------------------------+
| 1 | 23 | 5 | 213 |
| 2 | 23 | 5 | 214 |
| 3 | 23 | 5 | 215 |
| 4 | 23 | 5 | 216 |
| 5 | 23 | 6 | 217 |
| 6 | 23 | 6 | 218 |
| 7 | 23 | 6 | 219 |
| 8 | 23 | 6 | 220 |
| 9 | 55 | 13 | 221 |
| 10 | 55 | 13 | 222 |
| 11 | 55 | 16 | 223 |
| 12 | 55 | 16 | 234 |
| 13 | 55 | 22 | 235 |
| 14 | 55 | 22 | 256 |
| 15 | 55 | 22 | 261 |
| 16 | 62 | 13 | 272 |
| 17 | 62 | 13 | 273 |
| 18 | 62 | 24 | 277 |
| 19 | 62 | 24 | 278 |
| 20 | 62 | 24 | 288 |
| 21 | 62 | 31 | 289 |
| 22 | 62 | 31 | 290 |
+--------------------------------------+
Now what I wish is for each user_id
I want 2 rows of data but each row should have a different category_id
, like the below resultset:
+--------------------------------------+
| id | user_id | category_id | post_id |
+--------------------------------------+
| 1 | 23 | 5 | 213 |
| 5 | 23 | 6 | 217 |
| 9 | 55 | 13 | 221 |
| 11 | 55 | 16 | 223 |
| 16 | 62 | 13 | 272 |
| 18 | 62 | 24 | 277 |
+--------------------------------------+
The query I've used so far using GROUP BY
clause only manages to return a single row for each group, but I want 2 or possibly 3. Here is my query:
SELECT * FROM (
SELECT id, user_id, category_id, post_id
FROM my_table
GROUP BY user_id, category_id)
AS sub GROUP BY sub.user_id;
Please suggest how to go from here...