0

I need to make a list of all the items in the table feed and show only the first 2 users who subscribe to the content, but I can not put together a query that does the list only 2 users limit 2.

I've tried N querys and subquery, but could not get the expected result. The nearest was using group_concat, but if it concatenates all users and does not allow limited only to two initial, and would have to usesubstring_index for this purpose.

Query

select
  feed.id
, feed.type
, user.name

 from feed
 inner join user on user.id = feed.user
 group by feed.type

Result

Array(
    [0] => Array(
            [id] => 1
            [type] => Comedy
            [name] => Mike
        )

    [1] => Array(
            [id] => 3
            [type] => War
            [name] => John
        )

    [2] => Array(
            [id] => 6
            [type] => Terror
            [name] => Sophia
        )
)

Expected

Array(
    [0] => Array(
            [id] => 1
            [type] => Comedy
            [name] => Mike, Papa
        )

    [1] => Array(
            [id] => 3
            [type] => War
            [name] => John, Alex
        )

    [2] => Array(
            [id] => 6
            [type] => Terror
            [name] => Sophia, Jessica
        )
)
Papa Charlie
  • 625
  • 8
  • 31
  • 1
    You need to limit your result set, this is a [greatest-n-per-group](http://stackoverflow.com/questions/2129693/using-limit-within-group-by-to-get-n-results-per-group) problem. – Clockwork-Muse Aug 16 '15 at 14:13

3 Answers3

0
set @rn=0;
select id, type, name 
from 
(
select 
@rn:=@rn+1 AS r_n
,feed.id
,feed.type
,user.name
from feed
inner join user on user.id = feed.user
group by feed.id
order by feed.id) t
where t.r_n <= 2

You can generate row numbers per group and then select the first 2 rows per feed id.

Vamsi Prabhala
  • 48,685
  • 4
  • 36
  • 58
0

You can use variables to simulate row_number() to give each user per feed a "rank" and only select rows with number <= 2 before doing the grouping in order to only get 2 users per group:

select id, type, group_concat(name) from (
    select * from (
        select *, @rn := if(@prevFeedId = id, @rn+1, 1) as rn,
        @prevFeedId := id
        from (
            select
            feed.id
            , feed.type
            , user.name
            from feed
            inner join user on user.id = feed.user
        ) t1 order by id
    ) t1 where rn <= 2
) t1 group by id, type
FuzzyTree
  • 32,014
  • 3
  • 54
  • 85
0

I don't know exactly the schema of your tables but try the same approach you already tried with group_concat but join to a subquery like:

...
inner join 
(
  select user.id, user.name from user limit 2
) as x on x.id = feed.user
...
Manny
  • 69
  • 2
  • 10