mysql - SELECT 3 records per user group by on two columns -


i've been stuck in complex mysql query. here 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 wish each user_id want 2 rows of data each row should have different category_id, 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 far using group by clause manages return single row each group, want 2 or possibly 3. here query:

select * (     select id, user_id, category_id, post_id      my_table     group user_id, category_id)  sub group sub.user_id; 

please suggest how go here...

you can use user-defined variables give rank same user group , in outer query can simple use condition showing 2 categories per user or 3 or more need to

select id,   user_id,   category_id,   post_id,   rank  (select tt.* , @rank:= case when @group = user_id @rank + 1 else 1 end rank, @group:= tt.user_id (select    id,   user_id,   category_id,   post_id    table_name  group user_id,   category_id   order user_id,   category_id    ) tt  join (select @rank:=0,@group:=0) t1  ) new_t  rank <=2 /* give 2 records per user change 3 if need show 3 records per user */  

demo 2 rows per user

demo 3 rows per user


Comments

Popular posts from this blog

database - VFP Grid + SQL server 2008 - grid not showing correctly -

jquery - Set jPicker field to empty value -

.htaccess - htaccess convert request to clean url and add slash at the end of the url -