Skip to content
Advertisement

Select where in() for each id return equal rows count

How to select rows for each user_id equals select numbers of count for each user_id?

My example table:

mp3_id  |  user_id
--------------------
120     |  840
123     |  840
126     |  840
128     |  455
130     |  840
131     |  840
132     |  840
135     |  840
144     |  840
158     |  840
159     |  455
161     |  455
169     |  455
180     |  840
181     |  455
184     |  455
186     |  455
189     |  455

My simple query:

select mp3_id where user_id IN (840,455) limit 8

Return:

mp3_id  |  user_id
--------------------
120     |  840
123     |  840
126     |  840
128     |  455
130     |  840
131     |  840
132     |  840
135     |  840

But I want to this select:

mp3_id  |  user_id
--------------------
120     |  840
123     |  840
126     |  840
130     |  840
128     |  455
159     |  455
161     |  455
169     |  455

I want each user_id to return an equal row count. How to?

Advertisement

Answer

SELECT x.* 
  FROM my_table x 
  JOIN my_table y 
    ON y.user_id = x.user_id 
   AND y.mp3_id <= x.mp3_id 
 GROUP 
    BY x.mp3_id HAVING COUNT(*) <= 4 
 ORDER  
    BY user_id DESC
     , mp3_id;

or faster

SELECT mp3_id, user_id FROM
 (
 SELECT x.*, CASE WHEN @prev = user_id THEN @i:=@i+1 ELSE @i:=1 END i, @prev:=user_id FROM my_table x, (SELECT @prev:=null,@i:=1) vars ORDER BY user_id DESC, mp3_id
 ) a
 WHERE i<=4;
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement